How to configure the Yii2 UrlManager to handle rules with and without trailing slash

924 views Asked by At

I have a page like domain.com/calendar/2001/8/22, it can be visited by

domain.com/calendar/2001
domain.com/calendar/2001/8
domain.com/calendar/2001/8/22

It will show different content depending on URL.

I configured the urlManager rules:

'calendar/<year:[\-\d]+>' => 'calendar/view',
'calendar/<year:[\-\d]+>/<month:[\d]+>' => 'calendar/view',
'calendar/<year:[\-\d]+>/<month:[\d]+>/<day:[\d]+>' => 'calendar/view',

It's OK. But when I visit domain.com/calendar/2008/8/ (with the trailing slash, my website users often visit with trailing slash), I get 404.

How to configure the urlManager to handle rules with and without trailing slash?

2

There are 2 answers

0
ExploitFate On

Add 'suffix' => '/', just after 'enablePrettyUrl' => true,. Be aware that it will change all links on your site.

0
rob006 On

You should use UrlNormalizer to redirect "slash URLs" to "non-slash URLs" (or vice versa):

'urlManager' => [
    'enablePrettyUrl' => true,,
    'normalizer' => [
        'class' => 'yii\web\UrlNormalizer',
    ],
],

It will redirect all "slash URLs" to "non-slash URLs". If you want to use "slash URLs", you should set UrlManager::$suffix to /, then UrlNormalizer will redirect "non-slash URLs" to "slash URLs".

You can find more info about normalization in the guide.