skip to Main Content

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. /about-us.php to /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.

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:

if (preg_match("|^/about.php|", $_SERVER['REQUEST_URI'])) {
    Yii::$app->response->redirect('/about', 301)->send();
    return;
}

3

Answers


  1. Chosen as BEST ANSWER

    Just found the answer myself. My bootstrap attempt was not so bad, I just needed to add Yii::$app->end():

    if (preg_match("|^/about-us.php|", $_SERVER['REQUEST_URI'])) {
        Yii::$app->response->redirect('/about', 301)->send();
        Yii::$app->end();
        return;
    }
    

    Here is also another variant.


  2. 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!

    Login or Signup to reply.
  3. Yii 1.1

    public function actionOldPage()
    {
        Yii::app()->request->redirect('redirect/to/this', true, 301);
    }
    

    First I tried UrlManager in config/main.php

    ‘oldPage’=>’newPage’

    but it’s redirect as 302

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search