Home > Net >  How to set prefix to all keys of url rules?
How to set prefix to all keys of url rules?

Time:03-29

I want to set prefix for all keys of urlManager rules. At the moment I write rules like that:

'rules' => [
    'api' => '_public/site/index',
    'api/<controller>/<action>' => '_public/<controller>/<action>',      
     etc
]

I want to avoid copy/past-ing of api prefix to all rules. Because it could be 500 rules.

Is there a way to define somewhere a prefix in order to Yii placed it for every rule key itself?

$prefix and $prefixRoute is setting up prefix for values, but I want for keys.

Maybe this can be done by using .htaccess? But I don't know what should I write there.

CodePudding user response:

The yii\web\GroupUrlRule and its $prefix property is exactly what you are looking for.

In your case:

rules => [
    // ...
    new \yii\web\GroupUrlRule([
        'prefix' => 'api',
        'rules' => [
            '<controller>/<action>' => '_public/<controller>/<action>',
            // ... other /api/_ routes
        ],
    ]),
    // ... other rules
]

I'm not sure if adding rule like this '/' => '_public/site/index', into the group would work for /api route or if you would have to set that one explicitly outside of group rule. If you are going to set rule for /api outside of group rule it might be better to put it before the group rule.

CodePudding user response:

The GroupUrlRule with properties: prefix, routePrefix and rules will be enough. You can use it as follows:

new GroupUrlRule([
    'prefix' => 'api',
    'routePrefix' => '',
    'rules' => [
          '' => '_public/site/index',
          '<controller>/<action>' => '_public/<controller>/<action>',
    ]
])

Add this to the rules under urlManager in the main config file.

  • Related