【问题标题】:Yii2: Remove controller from URLYii2:从 URL 中删除控制器
【发布时间】:2017-01-14 05:47:12
【问题描述】:

我正在使用高级模板。 我在 SiteController 上创建了所有操作,所以我所有的 url 都是 domain.com/site/something,我需要从 url 中删除“site”这个词,所以它将是 domain.com/something。

我根据this question尝试了以下规则

'urlManager' => [
        'class' => 'yii\web\UrlManager',
        'showScriptName' => false,
        'enablePrettyUrl' => true,
        'rules' => array(
                '/<action:\w+>/<id:\d+>' => 'site/<action>',
                '/<action:\w+>' => 'site/<action>',
                '/noticia/<slug>' => 'site/noticia',
        ),
    ],

也基于this other question进行了尝试:

'urlManager' => [
        'class' => 'yii\web\UrlManager',
        'showScriptName' => false,
        'enablePrettyUrl' => true,
        'baseUrl' => 'http://localhost/websites/transcita/app/frontend/web',
        'rules' => array(
                [
                    'pattern' => '<action:\w+>',
                    'route' => 'site/<action>'
                 ],
                [
                    'pattern' => '<action:\w+>/<id:\d+>',
                    'route' => 'site/<action>'
                 ],
                '/noticia/<slug>' => 'site/noticia',
        ),
    ],

但两者都不起作用。当我输入 domain.com/something 时,我得到一个 404。 我也试过没有第一个 / 也没有用。

有什么想法吗?

【问题讨论】:

    标签: model-view-controller yii2 yii2-advanced-app friendly-url pretty-urls


    【解决方案1】:

    尝试:

    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'enableStrictParsing' => false,
        'rules' => [
    
            // ...
    
            // last rule
            '<action:(.*)>' => 'site/<action>',
        ],
    ], 
    

    【讨论】:

    • 谢谢!这非常有效!您是否碰巧有一个链接,我可以在其中阅读 \w+ 和 (.*) 之间的区别,因为该更改起到了作用。
    • 在这里您可以找到 reg expr 的出色解释:regex101.com。 \w+ 匹配任何字母、数字或下划线,而不是 .* 匹配零个或多个字符。也许你的动作不止一个词。
    【解决方案2】:

    另一种方式:

    'rules' => [
        '<alias:\w+>' => 'site/<alias>',
    ],
    

    【讨论】:

    • 这种方式更好,因为第一个答案为所有其他控制器(不是 SiteController)给出 404 错误
    猜你喜欢
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多