Yii2: Remove controller from URL

2019-07-18 17:34发布

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?

2条回答
一纸荒年 Trace。
2楼-- · 2019-07-18 17:50

Try with:

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

        // ...

        // last rule
        '<action:(.*)>' => 'site/<action>',
    ],
], 
查看更多
够拽才男人
3楼-- · 2019-07-18 17:54

Another way:

'rules' => [
    '<alias:\w+>' => 'site/<alias>',
],
查看更多
登录 后发表回答