Home : Internet : Server : Apache : Mod Rewrite : Force SSL Connection

Force SSL (https)

We can redirect all users who request a page via http:// to use an https:// connection, using a simple rewrite.

This code should be placed in the htaccess file in the root of your domain, i.e. domain.com/.htaccess

<IfModule mod_rewrite.c>
   Options +FollowSymLinks
   Options +Indexes
   RewriteEngine On
   RewriteCond %{SERVER_PORT}!^443$
   RewriteRule ^(.*)$ https://www.domain.com/$1 [R,L]
<
/IfModule>

The IfModule wrapper ensures we only execute this code if the mod_rewrite module is enabled. See portability notes for more information.

Inside the IfModule, the first three lines are discussed and explained in Start Rewriting (part one). All we are doing is ensuring we are ready to rewrite.

You may not always wish to use https, what if we only want to redirect if we are in a certain directory? Simply place that .htaccess code into the directory you wish to force a secure connection on, instead of placing it in the root of your domain.