Yii2 Clean URLs & Action Parameters

血红的双手。 提交于 2020-01-13 13:10:00

问题


I've enabled clean URLs on my Yii2 application, but I can't seem to get arguments to pass to the action.

I expect this:

localhost/app/web/a/b/c/d

To map to the following:

AController->actionB($c, $d)

It's not happening.

Here's my .htaccess:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule . index.php

The relevant part of my web.php:

'urlManager' => [
                'class' => 'yii\web\UrlManager',
                'enablePrettyUrl' => true,
                'showScriptName' => false,
                'rules' => array(
                        '<controller:\w+>/<id:\d+>' => '<controller>/view',
                    '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                    '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
                ),
        ],

回答1:


As far as I understand, the rule should look something like:

'<controller:\w+>/<action:\w+>/<c>/<d>' => '<controller>/<action>'

So if you try to access localhost/app/web/a/b/c/d, Yii will call:

class AController extends Controller
{
    public function actionB($c, $d)
    {
    }
}



回答2:


I suggest the following rule for your urlManager:

'rules' => [
    '<a:\w+>/<b:\w+>/<c:\d+>/<d:\d+>' => 'a/b'
],

Addressing to localhost/a/b/c/d should now call for action b inside controller a with params c and d.




回答3:


If you are expecting following URL.

localhost/app/web/a/b/c/d

To map to the following:

AController->actionB($c, $d)

you can specify main.php like following example.

You have to set URL rule like i have mentioned in the below example. It should work.

'urlManager' => [
                'class' => 'yii\web\UrlManager',
                'enablePrettyUrl' => true,
                'showScriptName' => false,
                'rules' => [
                        '<controller:\w+>/<action:\w+>/<id:\d+>/<id:\d+>' => 'a/b/c/d'
                ],
        ],

Please let me know if you have still any query.



来源:https://stackoverflow.com/questions/26854384/yii2-clean-urls-action-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!