Yii2:拦截404并将301重定向到新页面的最佳方法? [英] Yii2: Best method to intercept 404 and do 301 redirect to new page?

查看:509
本文介绍了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重定向到新页面的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆