How to redirect browser to https (ssl) in php

How to redirect the browser to https when site is using http protocal in PHP?

First of all, you should know that SSL must be installed 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

function redirectToHTTPS()
     $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

Above function is quite simple, you can call the function in that page where you’ve to redirect the browser to “https” .This function will preserver you script file name and query string in browser.

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.

  RewriteEngine On
  RewriteCond %{HTTPS} !on
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Just copy and paste the above code in .htaccess file then the whole website will be redirected to “https” when the browser is opened in “http” mode. The browser just get redirected using url rewriting in .htaccess.


Leave a comment