Liquid Hotdog

Directory and Host based SSL with Apache

So, I needed a way to simply force a user to use an SSL connection on various parts of my website. In this case, whenever they log in: /Login.jspa or when accessing their personal information: /myvv/ I've accomplished this by using Apache's mod_rewrite functionality.

In my directive for the host in question, I've added the following:

  1. RewriteEngine On
  2. RewriteCond %{SERVER_PORT} 80
  3. RewriteRule ^/myvv/(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
  4. RewriteRule ^/Login.jspa https://%{HTTP_HOST}/Login.jspa [R,L]

Firstly, we indicate that we do want to use mod_rewrite. We then ask it to apply the rules to any connection on port 80. Finnaly, I've set up two rules, one each for /Login.jspa and any files under /myvv/ For more information on the rewrite syntax, please see Apache's own documentation here

But now, I'd like to make sure the user returns to a normal unencrypted connection whenever they aren't accessing the above path and file. To do this, we need to add another set of rewrite rules to the SSL Host's directive. This time we'll match against anything that's NOT the above file and directory and redirect back to a non-secure connection.

  1. RewriteEngine On
  2. RewriteCond %{HTTP_HOST} ^* [OR]
  3. RewriteCond %{HTTP_HOST} ^*
  4. RewriteRule !^((/myvv/(.*))|(/Login.jspa))$ http://%{HTTP_HOST}%{REQUEST_URI} [R,L]

Again, you'll want to brush up on both mod_rewrite and regex to understand how this works.

-- MrBlaQ
Filed under: Main, Technology — August 23, 2007 @ 4:11 pm
Valid XHTML 1.0 Valid CSS 2
eXTReMe Tracker