【问题标题】:Yii2 301 redirect from raw url to SEO-friendly url in .htaccess doesn't work, need other solutionYii2 301 从原始 url 重定向到 .htaccess 中对 SEO 友好的 url 不起作用,需要其他解决方案
【发布时间】:2016-11-19 17:01:50
【问题描述】:

我有一个基于 Yii2 高级模板的站点,用于替换无法针对 SEO 优化的旧站点。

在 Yii2 的 urlManager 配置中启用了对 SEO 友好的 url。

出于 SEO 的目的,我应该为带有原始查询字符串和结构的 url 从旧​​站点编写近 20 301 个重定向:

/index.php?p=var
/index.php?p=open_cat&cat_id=55

到 SEO 友好的 url('contoller'、'action'、'alias' 是变量):

/controller/action/alias

我试过了:

  1. 在前端/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 错误。

  1. 在前端/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 与不同的操作和控制器相关联。

我很乐意提供提示或解决方案。谢谢!

【问题讨论】:

标签: php .htaccess redirect seo yii2


【解决方案1】:

解决方案取自 this question 上的回答。

我已经创建了组件 RedirectComponent,包含在组件和引导数组的 frontend\config\main.php 中:

<?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() 方法重定向到正确的位置,因此我通过本机 php header() 函数进行了重定向。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    相关资源
    最近更新 更多