PHP: Redirect HTTP to HTTPS.

This is a guide on how to force users to use your PHP application with HTTPS instead of HTTP. Over the past few years, HTTPS has risen in popularity – especially since Google announced that HTTPS was being used as a ranking signal for websites.

There are three ways to go about doing this. You can use PHP code to redirect users, you can use Apache’s Redirect directive or you can use Apache’s mod_rewrite module.

Using PHP.

Take a look at the following PHP code:

<?php

//If the HTTPS is not found to be "on"
if(!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != "on")
{
    //Tell the browser to redirect to the HTTPS URL.
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"], true, 301);
    //Prevent the rest of the script from executing.
    exit;
}

The code above is pretty simple. It checks the HTTPS variable in the $_SERVER superglobal array to see if it equal to “on”. If the variable is not equal to “on”, then it redirects the user to the HTTPS version of the current URL. It then uses the exit construct to prevent the rest of the PHP code from executing.

Obviously, you could add the PHP snippet above to a custom function so that you can call it at the top of all of your scripts.

Using Apache’s Redirect.

If you are using Apache web server and you have access to the Virtual Hosts file, then you can make use of the Redirect directive:

<VirtualHost *:80>
    ServerName www.mywebsite.com
    Redirect / https://www.mywebsite.com/
</VirtualHost >

<VirtualHost *:443>
    ServerName www.mywebsite.com
    #configure your SSL
</VirtualHost >

In the configuration above, we redirect all traffic on port 80 to port 443 (the default port for HTTPS).

Using Apache’s mod_rewrite.

If you’re using shared hosting and you don’t have access to your Apache configuration files, then you can create a .htaccess file in the main public root of your website:

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

The above .htaccess file will “rewrite” the URL to the HTTPS version if HTTPS is found to be off.

Hopefully, you found this guide useful!

See also: