Thursday, February 1, 2018

Force Heroku PHP app to use https for both www and non-www versions

Leave a Comment

I have a PHP app on Heroku with an SSL certificate for the www version of the domain name. I need all requests (to both www and non-www) to go to via https, and I have added .htaccess to that affect. However, there are still circumstances where it's possible for a user to access the http version and I don't understand why.

Here is my .htaccess:

RewriteEngine on  RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$ RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R] 

My understanding is that this should force all users to access via https://www, but that doesn't always happen. For example, Google sometimes provides search results without the https and the links open insecure http instead.

Any ideas about what I'm doing wrong?

2 Answers

Answers 1

first redirect to the same host-name on :443, then redirect to www.. ordinary www. is just an alias in DNS, while most use the shorter non-www hostname for websites. you might have to extend the certificate, because it requires both host-names explicitly added, unless it's wild-carded.

one does not have to filter for the host-name:

RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

also see this answer here, concerning robots.txt with enforced SSL.

Answers 2

Try the following rules and let me know if it works or not these rule will use https request instead of http or www and non-www version. The following rule will now redirect the user to the something like this.

https://www.example.com/

RewriteEngine On  RewriteCond %{HTTP_HOST} !^www\. [NC,OR] RewriteCond %{HTTPS} !on RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE] 

Hope this will help to achieve what you wanted

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment