I want to force SSL on my website.
I have a bunch of rewrite rules in the web root /
htaccess file needed for the live site, so I’ve isolated my testing to a /test
folder with an htaccess file inside it.
In the test
htaccess, I don’t have RewriteOptions Inherit
so the root rewrite rules are not applied. To verify that, I added a rule in the root htaccess that rewrites test
to a non existent page. If I remove the htaccess under test
, I get the expected 404. If I add it back, I no longer get 404. Therefore, the root rule (and all the rest) is not applied and doesn’t mess with the SSL thing.
So here’s what I have in test/.htaccess
:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=302]
When I navigate to example.com/test
, I get redirected to https://example.com/test/
with error ERR_TOO_MANY_REDIRECTS
.
However, If I use the query string as a flag to prevent multiple redirects:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{QUERY_STRING} !rd
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}?rd [R=302]
I successfully get redirected from example.com/test
to https://example.com/test/?rd
with no errors and I can see the HTML page there.
It appears that this rule:
RewriteCond %{HTTPS} off
doesn’t work correctly.
Questions
What is the problem? How do I fix it? Is it some server configuration error?
Edit: When I var_dump($_SERVER['HTTPS'])
, I get NULL
when on http and on
when on https. It’s never off
. However, even if I change the rule from:
RewriteCond %{HTTPS} off
to:
RewriteCond %{HTTPS} !=on
I still get the error.
Also, I’m testing with developer tools open, disabled cache and in incognito mode. That’s also the reason I’m using 302
redirect instead of 301
- to prevent caching.
Edit 2: Apache version is 2.2.22 and I’m not allowed to update it. This means I can’t use:
RewriteCond %{REQUEST_SCHEME} http$
as suggested.
Edit 3: I used Hurl.it to get the response headers from test
under http:
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 110
Content-Type: text/html; charset=UTF-8
Date: Mon, 05 Feb 2018 15:12:07 GMT
Server: nginx
Vary: Accept-Encoding