HOWTO - Forcing SSL Connections with .htaccess and mod_rewrite

by Chris Olstrom

in HOWTO

Warning! Forcing SSL use like this can cause more problems than it may be worth. Anything that is not SSL-aware will be unable to view your site. This can break compatibility with web services (see the example of FeedBurner below, including a workaround), search spiders (many may regard SSL-enabled content as private, and not index it), primitive scrapers (this is a good thing), certain desktop feed readers and blog publishing tools, and more.

If you have SSL support enabled (either with a verified SSL certificate, or a self-signed one), you can require all connections to your site to use SSL with a .htaccess file. Note that this uses mod_rewrite.

Requirements

  • Web Server running Apache
  • mod_rewrite installed and active
  • An SSL certificate installed and configured
  • Read/Write permissions on the file ‘.htaccess’ in whatever directory you are configuring

Enable mod_rewrite if you have not already done so, by adding the following line to your .htaccess file:


RewriteEngine On

Important Note! Setting RewriteEngine On multiple times in the same file or in multiple files (such as in a subdirectory) can trigger Internal Server Errors. If some (or all) pages return an HTTP 500 status code after enabling this, check to see if it is already enabled in the current .htaccess, or in the parent directory (check all the way back until you hit your DocumentRoot (usually public_html).

With it enabled, we can check which port the request is for (by default 80 is HTTP, 443 is HTTPS). If it is HTTP, silently rewrite the request to HTTPS:

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

As mentioned about, this can cause problems with RSS feeds. For example, FeedBurner is not SSL-aware at the time of this writing, and is unable to parse feeds that have SSL enforced like this. For the specific case of FeedBurner, add the following line before the RewriteRule line:

RewriteCond %{HTTP_USER_AGENT} !FeedBurner [NC]

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google