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

问题描述

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

解决方法

您可以创建一个实现yii \ web \ UrlRuleInterface的类。该接口需要两个功能:

  1. parseRequest:使用此方法检查请求是否匹配旧的url。如果是这样,则重定向到新的URL,否则返回false。您可以根据自己的喜好检查数据库表或旧网址列表。
  2. createUrl:由于这些旧网址不再起作用,因此createUrl只需要返回false。
public function createUrl($manager,$route,$params)
{
    return false; // this rule does not apply
}

此外,我会将其作为您的UrlManager规则的最后一条规则,这样它就不会影响您的其他页面,无论是在性能还是隐藏新的网址。

有关完整说明,请参见Yii上的文档:https://www.yiiframework.com/doc/guide/2.0/en/runtime-routing#creating-rules

,

我会将旧的URL添加到config/url-manager.php(如果使用高级模板,则添加到backend/config/url-manager.php),以通过适当的控制器操作对其进行处理,并在控制器中进行重定向。

一个示例,假设启用了漂亮的URL,旧的URL为posts/list,而新的简单的posts,则将以下内容添加到url-manager中的规则中:

'posts/list' => 'posts/post/index-redirect','posts' => 'posts/post/index',

这会将旧的URL路由到posts模块的PostController。将以下操作添加到控制器:

public function actionIndexRedirect()
{
    return $this->redirect(['index'],301);
}

当然,您可能会有很多旧的URL,并且您不想一一处理它们,而是向规则中添加参数并在重定向操作中处理参数。

,

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

方法1:

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

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

$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

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

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
        }
    }
});

Here也是另一个变体。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...