I can't seem to get pretty urls to be generated properly. My frontend config is as follows:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'item/<id:\d+>/<slug>' => 'item/view',
'category/<id:\d+>/<slug>' => 'category/view',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
]
],
The following url array:
['item/view', 'id' => 4, 'slug' => 'shark-chomp-socks']
generates the url http://example.com/item/4?slug=shark-chomp-socks
instead of http://example.com/item/4/shark-chomp-socks
.
If I manually type in the expected url (http://example.com/item/4/shark-chomp-socks
), the url resolves correctly without any errors.
How can I get it to generate the url properly?
The rules in my common config were causing the issue. I removed the urlManager
entry in common/config/main.php
and the urls were created properly. I had this in common/config/main.php
:
'urlManager' => [
'enablePrettyUrl' => true,
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
]
],
Since, the frontend/config/main.php
is merged into common/config/main.php
in my frontend/web/index.php
, the rules in frontend
were appended to those in common
and duplicates removed resulting in the following order:
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'item/<id:\d+>/<slug>' => 'item/view',
'category/<id:\d+>/<slug>' => 'category/view',
]
TL;DR: Remove any rules from any config file that is loaded before the one in which your custom rules are.