yii2 routing - pass parameter to route in rules

2019-06-16 06:03发布

When a user accesses domain/page, I need to route them to controller/action/100. I don't want to pass any parameter through the URL, but want to add it in url rules.

I added the code below to my config file.

'urlManager' => [
    'rules' => [
        'login' => 'site/login',  // working
        'about' => 'cms/page/10'  // Not Working
        'about' => 'cms/page?id=10'  // Not Working
    ],
],

The first rule is working fine.

Can I pass the parameter for the route in url rules?

1条回答
在下西门庆
2楼-- · 2019-06-16 06:42

You need to use defaults and declare the rule explicitly:

'urlManager' => [            
    'rules' => [
        'login' => 'site/login',
        [
            'pattern'  => 'about', 
            'route'    => 'cms/page',
            'defaults' => ['id' => 10],
        ]  
    ],
],

Add 'mode' => \yii\web\UrlRule::PARSING_ONLY to this rule if you want to prevent the transformation when you create a URL with the UrlManager (e.g. Url::to() uses the UrlManager and its rules and works in the opposite direction, that is Url::to(['cms/page', 'id' => 10]) will generate a link about)

Also consider to configure a redirect at your web server instead.

查看更多
登录 后发表回答