How to get Drupal 7 to Always Force https

Sunday, August 13th, 2017
Last Updated:
Sunday, August 13th, 2017

Disclaimer: Accessing the information on this page means you agree to the Sites Terms of Service

By default, Drupal does a decent job of dealing with https, however the .htaccess settings for it, don't do a good job of forcing it. What I mean by this, is that sure, you can point to your site on either the http or https, but it won't automatically force it to https. If you don't have users for your site or you aren't running an ecommerce site, this isn't that big of a deal, but when you do need the https for every single visitor, Drupal doesn't like to force it.

What I found is a very simple condition and rule that needs to be added to the .htaccess, UNDER your WWW / non-WWW rules. I'll show you the code, then give you the examples of where to use it.

Add The following under your www / non-www rules:

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

That's it! This will check to see if the protocol is http or https, and if http is "on", run it through the rule to force it to https instead.

For an example of forcing WWW on the domain:

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

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

So, how it works is pretty simple. The request comes in on Your rule says "No, show it as". So it switches it to Then it says "If http, switch to https". Since the previous rule says to force the www, that's what gets sent to the next rule to check for the http. That's why you don't "need" the www for that rule, because it was already there and forced by the previous rule so you end up with

In a perfect world, this would already be in the .htaccess files for a default Drupal 7 install, commented out. Don't ask me why this has been overlooked for the last *cough* decade...

So, that's it! Add two lines of code and you're golden. You'll always be sent over to the https version of your site, regardless of what the user types into the address bar and you don't even have to go into the settings.php file and add that https = true statement or whatever it is.

Post Comment