Yii2: Remove controller from URL

醉酒当歌 提交于 2019-12-13 14:16:59

问题


I am using the advanced template. I created all my actions on the SiteController, so all my urls are domain.com/site/something, and I need to remove the word "site" from the url so it will be domain.com/something.

I tried the following rules based on 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',
        ),
    ],

also tried this based on 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',
        ),
    ],

but neither is not working. I get a 404 when I type domain.com/something. I also tried without the first / and it didn't work either.

Any thoughts?


回答1:


Try with:

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'enableStrictParsing' => false,
    'rules' => [

        // ...

        // last rule
        '<action:(.*)>' => 'site/<action>',
    ],
], 



回答2:


Another way:

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


来源:https://stackoverflow.com/questions/39354593/yii2-remove-controller-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!