Redirect HTTP to HTTPS Apache secure connection

Most of the e-commerce website uses payment gateway for online payment. And, those sites uses SSL (secure socket layer) connection to transfer data to and from the payment gateway.

Most of the sites uses “http” protocol and you can see “http” in the browser’s address bar. But in the Ssl connection, we need to redirect the browser to “https” which means that “Hypertext Transfer Protocol over Secure Socket Layer”.

How to redirect the browser to https in PHP?

First of all, you must be installed SSL in the server. To redirect the browser to “https”, we must know that the site is using SSL or not at the moment. And for this, there is a server variable in PHP called “HTTPS”. $_SERVER[‘HTTPS’] returns “on” values when the site is using SSL connection.

Function to redirect the browser to “https” in PHP

<span style="color: #000000;"><span style="font-family: Times New Roman;">function redirectToHTTPS()</span></span>
<span style="color: #000000;"><span style="font-family: Times New Roman;">{</span></span>
<span style="color: #000000;">  <span style="font-family: Times New Roman;">if($_SERVER['HTTPS']!="on")</span></span>
<span style="color: #000000;">  <span style="font-family: Times New Roman;">{</span></span>
<span style="color: #000000;">     <span style="font-family: Times New Roman;">$redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];</span></span>
<span style="color: #000000;">     <span style="font-family: Times New Roman;">header("Location:$redirect");</span></span>
<span style="color: #000000;">  <span style="font-family: Times New Roman;">}</span></span>

Above function is quite simple, you can call the function in that page where you’ve to redirect the browser to “https”.

Redirecting whole website to “https” using .htaccess

You can call the above function in each and every page to redirect the browser to “https”. But rather than doing so it will be better to write three line of code in .htaccess file to redirect the whole website to use SSL connection throughout the pages.

<span style="color: #000000;"><span style="color: #111111;"><span style="font-family: Consolas,Andale Mono,Monaco,Courier,Courier New,Verdana,sans-serif;"><span style="font-size: x-small;">RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}</span></span></span></span>

No comments

Leave a Reply

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