我有一个基于 Yii2 高级模板的站点,用于替换无法针对 SEO 优化的旧站点。
在 Yii2 的 urlManager 配置中启用了 SEO 友好的 url。
出于 SEO 目的,我应该从旧站点编写近 20 301 重定向,以获取具有结构的原始查询字符串的 url:
/index.php?p=var
/index.php?p=open_cat&cat_id=55
到 SEO 友好的 url('contoller'、'action'、'alias' 是变量):
/controller/action/alias
我试过:
在前端/web/.htaccess 中:
RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d Redirect 301 /index.php?p=open_cat&cat_id=55 http://example.com/controller/action/alias RewriteRule . index.php
此方法无效,带有/index.php?p=open_cat&cat_id=55 url 的页面响应 404 错误。
在前端/web/.htaccess 中:
RewriteEngine on RewriteCond %{QUERY_STRING} p=open_cat&cat_id=55 RewriteRule ^index.php$ /controller/action/alias [L,R=301] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php
此方法使用原始路由附加 index.php 的完整路径:
http://example.com/path-to-file-from-server-root/app/frontend/web/index.php?r=controller/action/alias
我不知道如何使用 Yii2 方法为原始 url 编写正确的重定向。 另一个问题是新旧 url 没有任何共同点。 我为所有重定向搜索统一的解决方案,因为新的 url 与不同的操作和 Controller 相关联。
我很乐意提供提示或解决方案。谢谢!
最佳答案
解决方案取自 this question 上的答案.
我已经创建了组件 RedirectComponent,包含在 frontend\config\main.php 的组件和 Bootstrap 数组中:
<?php $params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php') );
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'homeUrl' => '/',
'bootstrap' => ['RedirectComponent','log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
/* */
'RedirectComponent' => [
'class'=>'frontend\components\RedirectComponent',
],
],
'params' => $params,
];
我在 RedirectComponent 类中创建了方法 init() (不确定是否需要在其中的 parent::init() 上):
public function init()
{
/*redirect logic*/
}
我无法通过 redirect() 方法重定向到正确的位置,通过动态创建的 Controller 和操作调用,所以我通过 native php header() 函数重定向。
关于php - Yii2 301 从原始 url 重定向到 .htaccess 中的 SEO 友好 url 不起作用,需要其他解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38413824/