Hello! Please tell me how you can handle error 404 in yii2.
With the wrong route, I need to redirect with the same route only to another domain.
For example:
newsite.ru/a/b/c - if this link is not correct, then the handler on the newsite (works on yii2) should redirect to oldsite.ru/a/b/c.

  • Well, when you have a 404 some kind of event in yii, catch it and make a stupid header('Location:http://oldiste.ru'.$_SERVER['REQUEST_URI']) . But before that, it’s worthwhile to request a page from the old site. There wasn’t a redirect to 404. - Naumov
  • The problem is that I do not know how to catch this event. - QWERTY
  • see yii is exception yiiframework.com/doc-2.0/yii-base-invalidrouteexception.html i.e. You can catch it and already there to work. - Naumov
  • Then another question: where to catch this exception? those. in which method? - QWERTY
  • Then I think we should wait for the specialists on yii. I didn’t work with him, but in principle you can try{}cath(invalidRouteException $error) {} right in index.php. But again, it is worth waiting for experienced specialists in this matter. - Naumov

2 answers 2

So far I have done this:
In the config pointed action handler

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

In the action handler

 public function actionError() { $exception = Yii::$app->errorHandler->exception; if ($exception !== null) { if ($exception->statusCode === 404) { //Меняем statusCode 3 $exception->statusCode = 301; return $this->redirect('http://oldsite.ru' . Yii::$app->request->url, 301); } return $this->render('/site/error', ['exception' => $exception]); } } 

But I do not like this decision. I would like not to create a handler in the controller, but to move it somewhere to a more independent place.

  • And what prevents yii \ base \ controller from inheriting and setting actionError in it, and inheriting its controllers from the latter? Thus, all the controllers will have an action error that can be fixed in one place. - ilyaplot
  • I also thought about this, but my base controller is in common / controllers /. If I specify this path in errorHandler, then I think yii will not be able to find it. - QWERTY
  • yiiframework.com/doc-2.0/yii-web-erroraraction.html The documentation says how to specify the error handling class through the actions in the controller. - ilyaplot

I think that you can still look in the side of the event in the application config
"as afterRequest" , and in it to check came the answer 200 or 404.
Or do as you wrote above.