[英]Yii2: how to redirect old URLs with 301?
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.我有一些来自旧版本网站的 URL,由于 SEO 目的,我想重定向到 Yii2 中的新 URL,例如。
/about-us.php
to /about
. /about-us.php
到/about
。 How do I do that?我该怎么做?
I can't use .htaccess
, and I can't use urlManager
rules because HTTP response status 301 needs to be set.我不能使用
.htaccess
,也不能使用urlManager
规则,因为需要设置 HTTP 响应状态 301。
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:我在引导程序类中尝试了以下操作,但即使代码执行,我在访问旧 URL 时仍然只得到 404:
if (preg_match("|^/about.php|", $_SERVER['REQUEST_URI'])) {
Yii::$app->response->redirect('/about', 301)->send();
return;
}
there is a cleaner and easier way to do it:有一种更干净、更简单的方法来做到这一点:
class MyController extends Controller
{
public function beforeAction($action)
{
if (in_array($action->id, ['about-us'])) {
Yii::$app->response->redirect(Url::to(['about']), 301);
Yii::$app->end();
}
return parent::beforeAction($action);
}
}
Hope that will be helpful!希望这会有所帮助!
Just found the answer myself.刚刚自己找到了答案。 My bootstrap attempt was not so bad, I just needed to add
Yii::$app->end()
:我的引导尝试还不错,我只需要添加
Yii::$app->end()
:
if (preg_match("|^/about-us.php|", $_SERVER['REQUEST_URI'])) {
Yii::$app->response->redirect('/about', 301)->send();
Yii::$app->end();
return;
}
Yii 1.1易 1.1
public function actionOldPage()
{
Yii::app()->request->redirect('redirect/to/this', true, 301);
}
First I tried UrlManager in config/main.php首先我在 config/main.php 中尝试了 UrlManager
'oldPage'=>'newPage' 'oldPage'=>'newPage'
but it's redirect as 302但它重定向为 302
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.