0

I need configure my Yii2 UrlManager rules like this:

  1. change http://domain/site/action to http://domain/action
  2. change http://domain/module/default to http://domain/module

so far what I have done:

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '<module:(!site)>' => '<module>/default',
        '<action:\w+>' => 'site/<action>',
    ],
],

when I trying access module it return 404. But when I remove '<action:\w+>' => 'site/<action>', access module again will show as module/default page. So how to solve this?

3
  • When you have url like http://domain/something how is the router supposed to know if something should be module or action? Commented Nov 16, 2020 at 8:14
  • I don't know. so do you have solution for this? Commented Nov 17, 2020 at 5:10
  • Not really. There is no generic solution using existing router. You can make explicit routes for all actions in site controller then put generic route for modules as last rule. Another option is to extend yii\web\UrlRule and override its parseRequest method to check existence of action. Or you can simply add some prefix to your url so you can determine if route belongs to site controller or module. For example use http://domain/m/something for modules and http://domain/something for actions in site controller. Commented Nov 26, 2020 at 15:19

1 Answer 1

0

You can try this code

'<action:(about|contact)>' => 'site/<action>',

insted of this

'<action:\w+>' => 'site/<action>',

and it will not work then change sequence of rules

'rules' => [
    '<action:\w+>' => 'site/<action>', <-----------it will be first
    '<module:(!site)>' => '<module>/default',
],
Sign up to request clarification or add additional context in comments.

4 Comments

'<action:(about|contact)>' => 'site/<action>', i want all action in site controller not only about and contact
if I change '<action:\w+>' => 'site/<action>', to be first, when open mydomain/mymodule will return 404
if you use this '<action:\w+>' => 'site/<action>' then it will always find action in your site controller only. you can put all action in-----> '<action:(about|contact)|..|..|......>'
The generic approach won't work. This pattern <action:\w+> doesn't check the existence of action, it will simply treat everything that match expression \w+ as action in site controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.