yii2: UrlRule Problem with trailing slash (/)
Hi i have added a UrlManager rules like given below added to my config
'<project:[-a-zA-Z]+>/<controller:\w+>' => '<controller>',
'<project:[-a-zA-Z]+>/<controller:\w+>/<action:\w+>' => '<controller>/<action>',
If i then call a url like
/projectname/controllername/action (works)
/projectname/controllername (works pointing to the default action in the controller)
/projectname/controllername/ (with trailing slash doens't work)
But the Url with a trailing slash produces a 404 error on the SiteController.
This is because the UrlRule doesn’t match. if i change the UrlRule to the code below (\w* instead of \w+) the default controller action is called.
'<project:[-a-zA-Z]+>/<controller:\w+>/<action:\w*>' => '<controller>/<action>',
I also tested the UrlRules in yii1 but there the UrlRules from the top are also working with a trailing / in the Url but not in yii2.
So I guess there is some kind of “bug”. I Don’t Know if the trailing slashes are removed in the Request in yii1 but not in yii2. But there is clearly some difference between the 2 frameworks.
Regards Horizons
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 1
- Comments: 23 (14 by maintainers)
Commits related to this issue
- fix #7670 by: - resolve Url like in the original code - if request can not be resolved, try again with suffix (if any) - if request is then resolved, then redirect to the corresponding url To be able... — committed to dynasource/yii2 by dynasource 8 years ago
- Fixes #7670: Added `UrlNormalizer` for normalizing requests with and without trailing slashes — committed to yiisoft/yii2 by samdark 8 years ago
Could be done app-side like the following:
Add a route at last line
'<url:.+>/' => 'site/redirect',
and add a action
@samdark could you please take a look at my pull request? I hope it will help to solve the issue. I use this approach on sites I develop.
Another .htaccess rewrite rule before checking directory.
and the config for
UrlManager
, enablingsuffix
This redirect rule works for me in htaccess:
@gerpayt:
slash should be inside regular expression:
'<url:.+/>' => 'site/redirect'
some improvements: 301 redirect, baseUrl, one redirect in case of many slashes
@samdark then it should be an option to choose between with/without ending slash. And option to allow both for people who don’t care about seo. And maybe 404 as default option (for BC)?