Search code examples
phpyiiyii2yii-url-manager

Yii User-friendly url and keep the old get format working


I set to the main config the following url rules:

    'urlManager'=>array(
        'urlFormat'=>'path',
        'showScriptName'=>false,
        'rules'=>array(
            '<controller:\w+>'=>'<controller>/list',
            '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
            '<controller:\w+>/<id:\d+>/<title>'=>'<controller>/view',
            '<controller:\w+>/<id:\d+>'=>'<controller>/view',
            '\?r=<controller:\w+>/<action:\w+>' => '<controller>/<action>'
        ),
    ),

Everything is woking fine, but I also want the previous url format to keep working so I don't have to rewrite lots of urls that I don't care it to be seo-friendly:

index.php?r=controller/action&param1=value1

But it shows an error now. Is there a way to keep it working?


Solution

  • To my opinion the best way is to replace all old urls with your IDE regex replace option. But anyway you can do what you want this way:

    1. Use following route rule in the urlManager config: 'rules' => [ [ 'class' => 'my\namespace\UrlRule', 'pattern' => '<controller>/<action>', 'route' => '<controller>/<action>', ], ...

    2. Extend yii\web\UrlRule with your my\namespace\UrlRule and rewrite its 'parseRequest' method so that it could use $_GET['r'] parameter value if is set:

        namespace my\namespace;
    
        class UrlRule extends \yii\web\UrlRule
        {
            public function parseRequest($manager, $request)
            {
                if ($pathInfo = \Yii::$app->request->get('r')) {
                    \Yii::$app->request->setPathInfo($pathInfo);
                }
                return parent::parseRequest($manager, $request);
            }
        }
    

    You may also extend yii\web\Request instead so that it's 'getPathInfo' method could use $_GET['r'] parameter if set.