Skip to content

How to Force Clients to Use HTTPS by PHP

PHP provides a global variable $_SERVER['HTTPS'] that can be checked whether the clients are connecting over SSL or not. For example:

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
if (!headers_sent()) {
header("Status: 301 Moved Permanently");
$https_url_rewrite = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $https_url_rewrite");

This can be very flexible, you can control the coverage of HTTPS enabled, even better, if you put the code snippet in a filter, you can control all incoming requests and pipe them to different HTTPS or HTTP URL.

If you'd like to force clients to use HTTPS by Apache, you may refer to this post: How to Force Clients to Use HTTPS by Web Server

Leave a Reply

Your email address will not be published.