【问题标题】:Pretty URL with yii2yii2 的漂亮 URL
【发布时间】:2015-03-08 03:07:10
【问题描述】:

我试图在 yii2 中启用漂亮的 url,但它不能按需要工作。

urlManager 配置:

'urlManager' => [
    'enablePrettyUrl' => true,
     'showScriptName' => false,
     'baseUrl' => '/',
]

public function actionIndex($custom_param)
{
    print($custom_param);
}

example.com/mycontroller?custom_param=value 完美运行。但我需要像example.com/mycontroller/value 这样的网址。

【问题讨论】:

    标签: yii yii2


    【解决方案1】:

    如果您想将此应用于mycontrollerindex 操作,并且如果custom_param 是整数,请将其添加到urlManagerrules 部分:

    `urlManager' => [
        'rules' => [
            'mycontroller/<custom_param:\d+>' => 'mycontroller/index',
        ],
    ],
    

    否则您可以修改模式以满足您的需要。

    例如,如果custom_param 是字符串,则将d+ 更改为w+

    如果你想将此规则应用到其他控制器,你可以这样做:

    '&lt;controller:(mycontroller|anothercontroller)&gt;/&lt;custom_param:\d+&gt; =&gt; '&lt;controller&gt;/index',

    在官方文档中阅读更多内容:

    【讨论】:

    • 如果自定义参数有特定值怎么办? i,e controller/action/1controller/action/ 换句话说,如果参数值具有特定值,则删除它。在分页和SEO中非常重要
    【解决方案2】:

    在您的 web.php 文件下面的组件中使用以下代码:

    'urlManager' => [
            'class' => 'yii\web\UrlManager',
            // Disable index.php
            'showScriptName' => false,
            // Disable r= routes
            'enablePrettyUrl' => true,
            'rules' => array(
                    '<controller:\w+>/<id:\d+>' => '<controller>/view',
                    '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                    '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ),
        ],
    

    在您的网络文件夹中创建一个 .htaccess 文件并将其粘贴:

    RewriteEngine on # If a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # therwise forward it to index.phpRewriteRule . index.php
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      • 2017-04-16
      • 2017-02-02
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      相关资源
      最近更新 更多