Htaccess URL重写到Yii2应用程序


Htaccess URL rewrite to Yii2 application

我的Yii2应用程序中有以下url结构

http://127.0.0.1/frontend/web/index.php?r=site%2Flogin
http://127.0.0.1/frontend/web/index.php?r=site%2Fpage2
http://127.0.0.1/frontend/web/index.php?r=site%2Fsample
http://127.0.0.1/frontend/web/index.php?r=site%2Fsignup

如何将该URL转换为类似的内容

http://127.0.0.1/login.php
http://127.0.0.1/page2.php
http://127.0.0.1/sample.php
http://127.0.0.1/signup.php

我应该删除frontend/web/index.php?r=site%2F

我试过了,但没有用

Options -Multiviews
RewriteEngine On
RewriteBase /
# Force search engines to use http://127.0.0.1/frontend/web/
RewriteCond %{HTTP_HOST} !^http://127'.0'.0'.1/frontend/web/$
RewriteRule ^(.*) http://127.0.0.1/frontend/web/$1 [R=301,L]
# Specify search friendly URLs
RewriteRule ^login'.php$ /index.php?r=site%2Flogin [L]

我也试过了,但也没用。

RewriteEngine on
RewriteRule ^frontend/web/index.php?r=site%2F([^'./]+) /$1.php [L]

无需更改.htaccess即可实现这一点。调整urlManager组件。将其添加到您的应用程序配置中:

'components' => [
    'urlManager' => [
        'enablePrettyUrl' => true, // Cancel passing route in get 'r' paramater
        'showScriptName' => false, // Remove index.php from url
        'suffix' => '.php', // Add suffix to all routes (globally)
    ],
    // Compare requested urls to routes
    'rules' => [
        'login' => 'site/login',
        'page2' => 'site/page2',
        'sample' => 'site/sample',
        'signup' => 'site/signup',
    ],
],

至于从所有其他路由中删除控制器部分,这违反了关键的MVC概念。

在这种情况下,您如何定义请求的操作属于哪个控制器?

如果是同名的行为,该怎么办?

例如:http://127.0.0.1/create.php-它应该加载site/create还是users/create

此外,我不确定这是否是一种好的做法,但你可以用规则的相同方式编写对所有路线的比较,但所有动作名称都应该是唯一的。

结论:如上所述,您可以将url修改为所需的视图,但只建议对默认控制器(SiteController)省略控制器名称。

官方文件:

  • UrlManager
  • $enablePrettyUrl
  • $showScriptName
  • $后缀
  • $规则
  • 路由和URL创建