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:

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:

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:

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!

Comments

comments