yii2yii2-basic-appyii2-urlmanager

Yii2 - UrlManager and params with hypens


I have the following URLs:

http://test.local/index.php?r=site%2Findex&slug=blog-detail
http://test.local/index.php?r=site%2Findex&slug=blog
http://test.local/

I want to get:

http://test.local/blog
http://test.local/blog-detail
http://test.local/ 

I am sending all requests to SiteController::actionIndex($slug), I am using Basic Application Template.

So far, I have been able to hide index.php and site/index.

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
       '<slug\w+>' => 'site/index',
    ],
]

But it seems \w+ does not match strings with -. Also if slug is empty it should show: http://test.local/.


Solution

  • \w does not match -. You need to use [\w\-] instead. And + requires at least one char in your case. You should use * instead:

    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
           '<slug:[\w\-]*>' => 'site/index',
        ],
    ]