Search code examples
yii2yii-url-manager

urlManager rules not working on modules Yii2


I am trying to make some url rules in Yii 2 so I can access an action from the controller like this:

controller/action/1 -> controller/action (with a parameter)

I tried some rules but they won't work in my modules (www.example.com/midend, www.example.com/backend).

So, if I want to access www.example.com/controller/action/1 it's works just fine but if I want to access www.example.com/midend/controller/action/1 it return 404.

These are the rules for modules:

'<module:\w+>/<controller:\w+>/<action:\w+>/<id:\w+>' => '<module>/<controller>/<action>',
'<module:\w+>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>',
'<module:\w+>/<controller:\w+>/<id:\w+>' => '<module>/<controller>',

These are the rules without modules:

'<controller:\w+>/<action:\w+>/<id:\w+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'<controller:\w+>/<id:\w+>' => '<controller>',

I already tried to replace <module:\w+> with midend.


Solution

  • Assuming your ids are integers, you should simply replace your rules by this one :

    '<controller>/<action>/<id:\d+>' => '<controller>/<action>',
    

    It will work for :

    • www.example.com/controller
    • www.example.com/controller/action
    • www.example.com/controller/action/1
    • www.example.com/module (assuming you have a default controller)
    • www.example.com/module/controller
    • www.example.com/module/controller/action
    • www.example.com/module/controller/action/1