Jeremy Sands

Res publica non dominetur

How to redirect to and from SSL in Apache

So … you have an e-commerce checkout page or a secure login thusly giving you the need to have an SSL page. But you don’t want people then staying in SSL the whole time, and adding an additional burden to your servers, do you? Here’s the simple solution, using mod_rewrite. The following two code snippets go into your apache virtualhost config files. This varies quite a bit by distro, but in Gentoo they’re in /etc/apache2/vhosts.d/

For the SSL virtualhost, add the following (between its tags obviously…)

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} !^[A-Z]{3,9}\ /(.*)TheEndOfTheURLOfPageToRedirect\.html\ HTTP/ [NC]
RewriteRule ^/(.*) http://%{SERVER_NAME}%{REQUEST_URI} [R]

This will redirect down from SSL all pages except those precious SSL needed pages. Just add additional lines like the 3rd if you have multiple pages that need SSL.

Now add the following to the regular non-SSL Virtualhost entry for the same site:


RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)TheEndOfTheURLOfPageToRedirect\.html\ HTTP/ [NC]
RewriteRule ^/(.*) https://%{SERVER_NAME}%{REQUEST_URI} [R]

Comment

*