For SEO purposes I want to redirect my old non-Yii2 URLs to the new ones. So I need to intercept the 404 that Yii throws and respond with a 301 redirection. Where is the best place to do that?
For SEO purposes I want to redirect my old non-Yii2 URLs to the new ones. So I need to intercept the 404 that Yii throws and respond with a 301 redirection. Where is the best place to do that?
3
Answers
So far I myself found these possible ways of doing it:
Method 1:
This method does it before the request is being handled - based on known URLs. They only take effect when the URL doesn't point to directly to existing files/folders (since otherwise
.htaccess
will never redirect the rquest to Yii).In
config/web.php
add the following to the config array:Method 2:
This method does it after the request has been handled - based on no route and having ended up with a 404. This has the advantage that we can also handle unknown URLs that ended up in a 404.
Add a bootstrap class as per documentation here and here. Then add this to your bootstrap() method:
Here is also another variant.
I would add the old URLs to
config/url-manager.php
(orbackend/config/url-manager.php
in case of advanced template) to process them by the appropriate controller action, and do the redirection in the controller.An example, assumed that pretty URL is enabled and the old URL is
posts/list
and the new one simpleposts
, than add the following to the rules inurl-manager
:This will route the old URL to the PostController of the posts module. Add the following action to the controller:
Of course you could have a lot of old URLs and you do not want process them one by one, than add parameters to the rule and process the parameters in the redirect action.
You could create a class that implements yiiwebUrlRuleInterface. You need two functions for that interface:
Also, I would put this as the last rule of your rules of the UrlManager so it doesn’t affect your other pages at all, in performance or hiding new urls.
See docs at Yii for full explanation: https://www.yiiframework.com/doc/guide/2.0/en/runtime-routing#creating-rules