Route to domain.com/nickname

I want to translate domain.com/nickname to domain.com/user/view, I made this code below that works however when there is some nickname with the same name as a controller there is no controller open.




        'urlManager' => [

            'enablePrettyUrl' => true,

            'showScriptName' => false,

            'rules' => [

                '<nick:\w+>' => 'user/view',

          ]



You can’t allow user to choose a nickname equal to your controller names, or change your url rules for example to domain.com/user/{nickname}.

I would personally make it be user/nickname but you can put all of your other controller rules first and users last as they match in order.

You will have to use very specific and not general rules for all of the other controllers. I would not do this if you have a lot of actions because this could make your app slow down or links with wrong urls. It will also make you prefix all of your other actions with the controller name and action in the URL but they must not match your user controller/action. I would not recommend this at all because it adds a lot of complexity for no gain but if you really need it to be domain/nickname it’s possible.

Thanks guys

I will block nicks registration equal to the names of controllers, creating a validation in the model that verifies if the controller exists.

I found two libs that return the list of existing controllers: dmstr/yii2-helpers and mithun12000/yii2-metadata

I made a mistake, controllers only open when there is a ‘slash’ at the end of the URL or when the action is specified.

What happens:

http://localhost/chart/ => http://localhost/chart/index [OK]

http://localhost/chart => http://localhost/user/view [FAIL]

Should I specify each controller before the nick rule? Any sugestions?




          'rules' => [

                '<controller:(chart|user)>' => '<controller>/index',

                '<nick:\w+>' => 'user/view',

          ],