且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-21 17:47:52

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

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

此处也是另一种变体.