3

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?

Rob
  • 128
  • 1
  • 7
  • 29
  • This might help [LINK](https://stackoverflow.com/questions/26489519/how-to-redirect-to-https-with-htaccess-on-heroku-cedar-stack) – Kaushik C Jan 26 '18 at 04:24
  • Thank you, I've just given that a try. Unfortunately, it is still possible to force my site to use http – Rob Jan 26 '18 at 04:45

2 Answers2

3

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.

# rewrite to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

if you want to rewrite all to www. (or whatever the certificate says), just add another rule below. at first access, the non-SSL rule [L] is the last step, at the next access the SSL rule [L] is the last step, of the rewrite.

# rewrite to www.
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

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

when it is "still possible to use HTTP" ...maybe consider another location for the .htaccess file - or create directories per host-name, which just redirect.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
  • Thank you @MartinZeitler I've added that to `.htaccess`, but it's still possible for me to visit the http version of the site without it redirecting. You mention moving `.htaccess` to another location. It is in the root folder at the moment, alongside `procfile` and `composer.json` – Rob Feb 03 '18 at 15:35
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

Mohsin Abbas
  • 630
  • 8
  • 29