Yii2: How to redirect on invalid routes?

542 views Asked by At

Instead of showing an error page I'd like to redirect the user to the start page in general, if the route is invalid (there is no controller/action like requested). To make it sound the redirection should only happen on 'normal' page requests. Though AJAX calls can be invalid as well, I don't want to send a redirect to the browser here.

How can I do this efficiently?

1

There are 1 answers

0
Maksym Fedorov On

You can override ErrorAction class and will implement necessary logic. For example:

class MyErrorAction extends \yii\web\ErrorAction
{

    public $redirectRoute;  

    public function run()
    {
        if (!Yii::$app->getRequest()->getIsAjax()) {
            Yii::$app->getResponse()->redirect($this->redirectRoute)->send();
            return;
        }
        return parent::run();
    }
}

After it, you should add this action in a controller and configure it

class SiteController
{
    public function actions()
    {
        return [
            'error' => [
                'class' => MyErrorAction::class
                'redirectRoute' => 'site/my-page'
            ],
        ];
    }
}

and configure the route of error action in the error handler

'errorHandler' => [
    'errorAction' => 'site/error',
]