Skip to content
Home » Web » How to Redirect HTTP to HTTPS

How to Redirect HTTP to HTTPS

We have 2 ways to redirect a HTTP connection to HTTPS

  1. Redirect HTTP to HTTPS by Web Server
  2. Redirect HTTP to HTTPS by PHP Code

Web Server

Apache httpd provides several ways to force clients to use secure https, one is redirect, the other is rewrite.

Redirect

Redirect is rather easy to understand by adding this line for instance to your httpd.conf

Redirect permanent /login https://mysite.example.com/login

But there's a drawback, if you want to secure the whole site, this approach cannot cover all situations.

Rewrite

Rewrite is a better way to do it.

[root@test ~]# vi /etc/httpd/conf/httpd.conf
...
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

Don't forget to restart httpd.

[root@test ~]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd: Apache/2.2.26 mod_ssl/2.2.26 (Pass Phrase Dialog)
Some of your private key files are encrypted for security reasons.
In order to read them you have to provide the pass phrases.

Server www.example.com:443 (RSA)
Enter pass phrase:

OK: Pass Phrase Dialog successful.
                                                           [  OK  ]

Although rewrite can cover more situations, httpd will become very busy in a production server.

PHP Code

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

<?php
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.

Leave a Reply

Your email address will not be published. Required fields are marked *