apache .htaccess files in Apache Force HTTPS


.htaccess can be used to force your HTTP site to redirect to HTTPS.

Here's a quick way that doesn't require editing the code for your domain:

RewriteEngine On
RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Warning: The code above assumes that you can trust %{HTTP_HOST} to point to your domain.

If you need to be sure that the redirect location is your domain, replace %{HTTP_HOST} with your domain.

The code above does this:

  1. Enable RewriteEngine.
  2. Continue if the current request is not using HTTPS.
  3. Do a HTTP 301 redirect to https://%{HTTP_HOST}%{REQUEST_URI}, where
    • %{HTTP_HOST} is the host requested by the browser and
    • %{REQUEST_URI} is the URI requested by the browser (everything after the domain).

Warning: Your web application must be able to handle HTTPS requests, and Apache for your host should be configured with a valid site certificate.

Note that it is significantly more efficient to simply do a Redirect in the http vhost than to do these multiple per-request comparisons in a .htaccess file. See http://wiki.apache.org/httpd/RedirectSSL for further discussion of this technique.