Rdirecting all urls to https in Yii2


I have been struggling using htaccess to perform redirects in my application to https for all urls. I am using the advanced template, and have a live site which is using a SSL certificate (which makes testing a bit difficult!).

I’ve tried using .htaccess but I get an error saying that the page is not redirecting properly. This is the htaccess I was using

RewriteEngine on

#First rewrite any request to the wrong domain to use the correct one (here www.)

RewriteCond %{HTTP_HOST} !^www\.

RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

If a directory or a file exists, use the request directly

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

Otherwise forward the request to index.php

RewriteRule . index.php

I am not an expert in htaccess at all, and given the problems I was facing with the page not redirecting properly as referenced above, I thought I might be able to achieve the same effect using Yii directly.

Having read this article https://github.com/yiisoft/yii2/issues/9116 which discussed adding $_SERVER[‘HTTPS’] = ‘on’ to the index.php file, I tried adding this to the backend folder index.php file - and I have secure urls without doing anything eg

(I am using www directly for the time being)

http://www.client-site-1.co.uk/backend => https://www.client-site-1.co.uk/backend

(Please note I don’t have a SSL on this domain at the moment!)

However, if I do the same on the front end index.php file I do not get the same behaviour

http://www.client-site-1.co.uk => http://www.client-site-1.co.uk

Of course $_SERVER[‘HTTPS’] = ‘on’ is used in the getIsSecureConnection function in \yii2\web\Request.php

Even if I return true from this directly, I still can’t get the same behaviour on the front end.

If I can get the htaccess to work correctly without the redirection problem that’s fine but I would like to use Yii2 directly if that’s possible!