Redirect http to https using Apache mod_rewrite

It’s required to have a URL with secure protocol while payment related pages. This payment mainly occurs in online shopping sites.

So what to do when you have developed you site with http and now user wants that all pages should be using https since here money comes into the play.

There are two ways.

  1. If you like unwanted hard work then, changes all links with https manually in all project code.
  2. But in smarter way you can do this with few lines without touching your source code.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Above code should be placed in your .htaccess file. This code will do all this things for you as you needed.

Here are the explanation of the code:

Line 1: RewriteEngine On
This line determine the Apache rewrite engine to start rewriting the urls as per the given rules.

Line 2 : RewriteCond %{HTTPS} off
This line will check for the current protocol of the url. This will return true if current protocol is http.

Here {HTTPS} is RewriteCond Directives. This is used to redirect based on certain condition.

Line 3: RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

This rule will be applied if and only if the rule in line 2 return the true, That means this rule will get apply if the current protocol is http. And this rule transfers the http to https.

Before using this tips make sure that your mod_rewrite module is enable in your apache conf file.

This code will redirect all pages of you website to https. But what if you want to redirect only some of you pages to https? I will describe this topic in my next post.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: