Yii2:如何使用 301 重定向旧 URL? [英] Yii2: how to redirect old URLs with 301?
问题描述
我有一些旧版网站的 URL,出于 SEO 的目的,我想重定向到 Yii2 中的新 URL,例如./about-us.php
到 /about
.我该怎么做?
I have some URLs from the old version of my site that I want to redirect to their new ones in Yii2 due to SEO purposes, eg. /about-us.php
to /about
. How do I do that?
我不能使用.htaccess
,也不能使用urlManager
规则,因为需要设置HTTP响应状态301.
I can't use .htaccess
, and I can't use urlManager
rules because HTTP response status 301 needs to be set.
我在 bootstrap 类中尝试了以下操作,但即使代码执行了,我仍然在访问旧 URL 时得到 404:
I tried the following in a bootstrap class but even though the code executes I still just get a 404 when going to the old URL:
if (preg_match("|^/about.php|", $_SERVER['REQUEST_URI'])) {
Yii::$app->response->redirect('/about', 301)->send();
return;
}
推荐答案
我自己刚刚找到了答案.我的引导尝试还不错,我只需要添加 Yii::$app->end()
:
Just found the answer myself. My bootstrap attempt was not so bad, I just needed to add Yii::$app->end()
:
if (preg_match("|^/about-us.php|", $_SERVER['REQUEST_URI'])) {
Yii::$app->response->redirect('/about', 301)->send();
Yii::$app->end();
return;
}
这里也是另一种变体.
这篇关于Yii2:如何使用 301 重定向旧 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!