Web Server

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.

[cc lang=”apache”]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
[/cc]

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.

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *