I have site based on Yii2 advanced template, made for replacing old site that cannot be optimized for SEO.
SEO-friendly urls are enabled in Yii2's urlManager configuration.
For SEO purposes I should write near 20 301 redirects from old site for urls with raw query string with structures:
/index.php?p=var
/index.php?p=open_cat&cat_id=55
to SEO-friendly urls ('contoller','action','alias' are variables):
/controller/action/alias
I have tried:
In frontend/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
This method didn't work, page with /index.php?p=open_cat&cat_id=55 url responds 404 error.
In frontend/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
This method appends full path of index.php with raw route:
http://example.com/path-to-file-from-server-root/app/frontend/web/index.php?r=controller/action/alias
I don't know how to write correct redirect with Yii2 methods for raw url. Also problem is that old and new urls have nothing in common. I search unified solution for all redirects, because new urls are associated with different actions and controllers.
I would be glad for hint or solution. Thank you!
Solution was taken from answer on this question .
I've created component RedirectComponent, included in frontend\\config\\main.php in components and bootstrap arrays:
<?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,
];
I've created method init() in RedirectComponent class (not sure in necessity on parent::init() in it):
public function init()
{
/*redirect logic*/
}
I couldn't redirect to proper location via redirect() method, called through dynamically created controller and action, so I've redirected via native php header() function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.