model-view-controlleryii2yii2-advanced-appfriendly-urlpretty-urls

Yii2: Remove controller from URL


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?


Solution

  • Try with:

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