Using mod_rewrite to force HTTPS-only transfers

Some websites require that all content be served securely using HTTPS. This is easily accomplished using Apache mod_rewrite directives. Just add the configuration below to a file named ".htaccess" in the root directory of your web site:

<IfModule mod_rewrite.c>

RewriteEngine On

# Add a trailing slash to directories and force SSL
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !(/$)
RewriteCond %{SERVER_PORT} 80
RewriteRule (.*) https://%{HTTP_HOST}/$1/ [R=301,L]

# Force SSL for file requests
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R,L]


Leave a Reply