Forcing SSL browsing in Apache

The Apache vhost configuration snippet below will force any non-SSL requests for a website to be rewritten to an HTTPS site instead. This is useful to ensure that clients cannot accidentally browse an insecure site, but they don’t have to remember or bookmark a particular URL.

ServerName secure.example.co.uk
ServerAlias www.example.co.uk
ServerAlias example.co.uk

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule ^/(.*) https://secure.example.co.uk%{REQUEST_URI} [R]

ServerName secure.example.co.uk
ServerAdmin admin@example.co.uk

DocumentRoot /var/www/secure.example.co.uk/htdocs
ErrorLog /var/www/secure.example.co.uk/logs/error.log

The “R” in the rule is a redirect flag that issues a 3xx redirect to the requesting browser. Because the redirect is fully-qualified the entire URI is returned, along with whatever page was requested. If a client requests http://example.co.uk/webmail/ the browser will be redirected to https://secure.example.co.uk/webmail/.

A quick check with curl shows the redirect issued by Apache:

david:~$ curl http://lionserver.co.uk -D -
HTTP/1.1 302 Found
Date: Fri, 20 Sep 2013 20:15:15 GMT
Server: Apache/2.2.16 (Debian) mod_ssl/2.2.16 OpenSSL/0.9.8o
Location: https://secure.lionserver.co.uk/
Vary: Accept-Encoding
Content-Length: 373
Content-Type: text/html; charset=iso-8859-1

Read more in the mod_rewrite documentation.

David Cannings
David Cannings
Cyber Security

My interests include computer security, digital electronics and writing tools to help analysis of cyber attacks.