adeade adeade - 3 months ago 48
PHP Question

Yii2 URL Route for make a Slug Url

I'm learning on yii2,
I have a problem when make a url route.
here's my url configuration

'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
// 'enableStrictParsing' => false,
'enablePrettyUrl' => true,
'rules' => array(
'category/<id:\S+>' => 'category/detail',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'request-password-reset' => 'site/request-password-reset',
'reset-password/<token:\S+>' => 'site/reset-password',
'profile/<id:[0-9a-zA-Z\-]+>/?' => 'profile/user',
'logout' => 'site/logout',
'login' => 'site/login',

),
],


The problem is in profile routing.
Here's the case:


  1. http://localhost/myapps/profile/some-url/ -> work with added slash in
    the end of url

  2. http://localhost/myapps/profile/some-url -> without slash in end of url isn't working and error 404

  3. http://localhost/myapps/profile/someurl -> not working error 404.

  4. http://localhost/myapps/profile/first-second-third -> with our without slash in the end is working



I'm really confuse, I've been looking for previous question here and try out nothing working with my case.

Can somebody help with my problem?

Answer

Just move your Profile alias to the top of the list:

'profile/<id:[0-9a-zA-Z\-]+>/?' => 'profile/user',
'category/<id:\S+>' => 'category/detail',  
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'request-password-reset' => 'site/request-password-reset',
'reset-password/<token:\S+>' => 'site/reset-password',  
'logout' => 'site/logout',
'login' => 'site/login',

As '<controller:\w+>/<action:\w+>' => '<controller>/<action>' was defined before 'profile/<id:[0-9a-zA-Z\-]+>/?' => 'profile/user', it will never reach profile, because it recognized it as a controller/action.

Comments