Enforce SSL for an Apache vhost

Here’s a proper way to enforce SSL with the apache2 web server, without hardcoding the ServerName in the config. You can also use this in a .htaccess file:

<IfModule mod_rewrite.c>
   <IfModule mod_ssl.c>
     RewriteEngine on
     RewriteCond %{HTTPS} !^on$ [NC]
     RewriteRule . https://%{HTTP_HOST}%{REQUEST_URI} [L]
    </IfModule>
 </IfModule>

You need the rewrite module and ssl module enabled (obviously), which can be easily enabled with the a2enmod commands:

a2enmod ssl
a2enmod rewrite
comments powered by Disqus