簡體   English   中英

Yii2 301從原始網址重定向到.htaccess中的SEO友好網址不起作用,需要其他解決方案

[英]Yii2 301 redirect from raw url to SEO-friendly url in .htaccess doesn't work, need other solution

我有基於Yii2高級模板的網站,用於替換無法針對SEO優化的舊網站。

在Yii2的urlManager配置中啟用了SEO友好的URL。

對於搜索引擎優化的目的,我應該寫舊網站的20 301重定向為url與原始查詢字符串結構:

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

對SEO友好的網址('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與不同的操作和控制器相關聯。

我很樂意提示或解決方案。 謝謝!

解決方案取自這個問題的答案。

我創建了組件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()函數重定向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM