Home  »  ArticlesGuidesHow ToTechnology   »   Using PHP to Redirect HTTP Traffic to HTTPS

Using PHP to Redirect HTTP Traffic to HTTPS

We published a guide showing how to force HTTPS using the Apache .htaccess configuration file. That is a system that works but is restricted to those using Apache as a web server. In today’s guide, we will show you how to use PHP to redirect HTTP to HTTPS.

The PHP solution provided here will work with different web servers including the mainstream ones such as Apache, Nginx, and IIS.

Like all redirects, bad configurations can cause endless redirect loop errors. This involves checking if

$_SERVER['HTTP_X_FORWARDED_PROTO']

or

$_SERVER['HTTPS']

variables exist or checking for a specific value of those variables.

The Working PHP Redirect HTTP to HTTPS Code

if (
       $_SERVER['HTTP_HOST'] != 'localhost' && // optionally disable on localhost
   !( 
       ( $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 ) ||  
           ( isset($_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&   
           $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' )
       ) 
   )
{
   $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
   header('HTTP/1.1 301 Moved Permanently');
   header('Location: ' . $redirect);
   exit();
}

There you have it, that is how you can use PHP to redirect HTTP to HTTPS.

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