Home  »  ArticlesGuidesHow ToTechnology   »   Using .htaccess to Redirect HTTP to HTTPS

Using .htaccess to Redirect HTTP to HTTPS

For obvious, or not so obvious security reasons, it is important to redirect all your web traffic from HTTP to HTTPS. There are various ways you can do it. However, in this guide, we shall take a look at how you can do it using Apache’s .htaccess rules.

.htaccess has got a somewhat strict syntax and therefore it is so easy to get things wrong with the slightest error. The other thing to note is that the various rules that are placed and processed in the file are done so in order from top to bottom.

With this in mind, it serves as a starting point to understanding where issues like the ‘ERR_TOO_MANY_REDIRECTS‘ originate from. Examples of causes of the aforementioned error include badly formed rules, where rules are affected by other sources such as Cloudflare or WordPress plugins that add additional conflicting rules to the same .htaccess file.

Another good example is found in WordPress where the ‘site_url’ and ‘home’ are defined in the admin dashboard as http://example.com instead of https://example.com. What happens here is WordPress redirects the website to HTTP and the .htaccess redirects the website back to HTTPS causing endless redirects.

The Redirect HTTP to HTTPS Fix

Place the following code above other rules in your .htaccess file. Just in case it already exists, the <IfModule mod_rewrite.c> ... </IfModule> part can be repeated multiple times in your file so it is okay to have it there.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

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

The above snippet will redirect HTTP to HTTPS before doing anything else that the rest of your file rules direct. There you have it.

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.

Available under:
Articles, Guides, How To, Technology