How to Redirect HTTP to HTTPS by Web Server

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

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

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

Leave a Reply

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