url-rewritingyii2yii2-basic-appyii-url-manager

Change/Rename Controller Name In URL: Yii2


I was looking to change controller name in URL. Which, we can do by renaming the controller name in module. But, Through URL manager if we can do it. It will be better.

Module: user, Controller: api, Action: index

Right now,

'urlManager' => [
  'enablePrettyUrl' => true,
  'showScriptName' => false,
  'rules' => [
        '<controller:(api)>/<action:\w+>/<id:[a-z0-9]+>' => 'user/<controller>/<action>',
        '<controller:(api)>/<action>' => 'user/<controller>/<action>',
    ]
];

And, I can access it through.

http://dev.example.com/api/index

But, I was looking to change it to

http://dev.example.com/world/index

How can I do it? Any help/hint/suggestion is appreciable.


Solution

  • You can create custom url rules by adding items to the rules array.

    So, in your case insert this into the rules array

    'world/index' => 'api/index'
    

    You can read more about URL rules here.