Monday , February 3 2025

How to add 301 redirect to https for Yii2 without .htaccess

I’ve tested different redirect options for .htaccess, but sites keep giving “redirected you too many times” error. Here is the working code to solve the problem.

In the file /config/web.php you need to find:

'bootstrap' => [
		'log',
		'app\components\Bootstrap',
	],

and place below:

'on beforeRequest' => function ($event) {
       if(!Yii::$app->request->isSecureConnection){
           $url = Yii::$app->request->getAbsoluteUrl();
           $url = str_replace('http:', 'https:', $url);
           Yii::$app->getResponse()->redirect($url);
           Yii::$app->end();
       }
},

About iryna

I'm Iryna, a web developer from Ukraine with a decade of experience solving complex technical challenges in the world of freelance. Throughout my career, I've worked on everything from troubleshooting server-side issues and optimizing website performance to enhancing user interfaces. On this blog, I share detailed solutions to the technical problems I’ve encountered and methods that have worked best for me. In addition to my technical expertise, I’m also passionate about digital drawing. I hope the tutorials and insights I provide here will help both fellow developers and creatives alike in their own projects.

Check Also

Display the date + a few days from the current one

The task in short: you need to make the delivery date + 5 days from …

Leave a Reply

Your email address will not be published. Required fields are marked *