Yii2:拦截404并将301重定向到新页面的最佳方法?

编程入门 行业动态 更新时间:2024-10-26 08:32:40
本文介绍了Yii2:拦截404并将301重定向到新页面的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

出于SEO的目的,我想将旧的非Yii2 URL重定向到新的URL.因此,我需要拦截Yii抛出的404并以301重定向进行响应.最好的地方在哪里?

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?

推荐答案

到目前为止,我本人已经找到了以下可行的方法:

So far I myself found these possible ways of doing it:

方法1:

此方法在处理请求之前 -基于已知的URL.它们仅在URL不直接指向现有文件/文件夹时才生效(否则,否则.htaccess绝不会将rquest重定向到Yii).

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).

在config/web.php中,将以下内容添加到配置数组中:

In config/web.php add the following to the config array:

$config = [ 'id' => '...', 'components' => '...', 'params' => '...', ... 'on beforeAction' => function($event) { $redirects = [ 'your/old/url.php' => '/my/new-route', 'contact.php' => '/site/contact', ]; if (($newRoute = $redirects[Yii::$app->requestedRoute]) || ($newRoute = $redirects[Yii::$app->requestedRoute .'/'])) { // maybe you want to add some logging here on this line Yii::$app->response->redirect(\yii\helpers\Url::to($newRoute), 301); Yii::$app->end(); } }, ];

方法2:

此方法在请求被处理后 进行处理-基于无路由,并以404结尾.这具有的优势是,我们还可以处理以404结尾的未知URL

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.

根据文档此处添加引导类此处.然后将其添加到bootstrap()方法中:

Add a bootstrap class as per documentation here and here. Then add this to your bootstrap() method:

Yii::$app->on(\yii\web\Application::EVENT_BEFORE_ACTION, function($event) use (&$app) { if ($event->sender->getStatusCode() == 404) { // maybe you want to add some logging here on this line if (in_array($app->requestedRoute, ['your/old/url.php', 'contact.php'])) { // determine new route and redirect the same way as we do in method 1 } else { // here you do redirect eg. to the homepage or do nothing if you still want to throw a 404 } } });

此处也是另一种变体.

更多推荐

Yii2:拦截404并将301重定向到新页面的最佳方法?

本文发布于:2023-11-01 19:51:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并将   到新   重定向   页面   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!