Search code examples
phpyii2yii2-advanced-app

Yii2: How to redirect to with UrlManager?


In my Yii2 config I have:

'components' => [
    'urlManager' => [

        'baseUrl'         => '',
        'enablePrettyUrl' => true,
        'showScriptName'  => false,

        'rules' => [
            'search' => 'site/index',
            ...
        ],
    ...

If I go to site.com/search it works. If I go to site.com/site/index it also works and shows the same content. How to redirect the call instead of just showing the response of site/index? It must also redirect with params (site.com/site/index?param=1 -> site.com/search?param=1)


Solution

  • The UrlManager does not redirect. It rather does a rewrite like a web server. It is called routing.

    If you would like to do a redirect in your code you can use Response::redirect(). If you don't have a SearchController where you can put this statement in an action, you can place it into the beforeAction event. You can do this in your configuration array:

    Option #1

    [
        'components' = [
            ...
        ],
        'on beforeAction' => function ($event) {
            if(Yii::$app->request->pathInfo === 'search') {
                $url = 'site/index?' . Yii::$app->request->queryString;
                Yii::$app->response->redirect($url)->send();
                $event->handled = true;
            }
        }
    ]
    

    Option #2

    Or if you have SearchController use:

    class SearchController extends \yii\web\Controller {
        public function actionIndex() {
            $url = 'site/index?' . Yii::$app->request->queryString;
            return $this->redirect($url);
        }
    }
    

    Option #3

    Third option is to configure the web server to do the redirect. That would be the fastest solution.