Sunday, September 11, 2011

How to automatically redirect HTTP to HTTPS in Apache

Redirecting HTTP to HTTPS is one common and popular way to protect user privacy and sensitive information without making user typing 'https' manually to access your site.

First, we verify that Apache is configured for HTTPS connection and necessary SSL certificates are already in placed.

Then, either we use redirect or mod_rewrite.

  • Using mod_rewrite. Add these directives to your configuration file:
  •           RewriteEngine On
              RewriteCond %{SERVER_PORT} !^443$
              RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [L,R]
    Make sure you have loaded mod_rewrite module into Apache.

  • Using redirect. Add these directives to your configuration file:
  •           SSLRequireSSL
              Redirect permanent /secure https://www.domain.com/secure


The 2nd method which uses redirect uses one less module, so security wise could be better. In addition, you don't need to worry about re-writing on logs and etc. Now we restart Apache and go test it out.

No comments: