Joe's Linux Blog Linux Admin tips and tricks

May 18, 2010

Apache HTTP to HTTPS redirection with mod_rewrite

Filed under: Configuration,Web Publishing — jfreivald @ 5:00 pm

I was trying to enforce ssl for my mail server, which runs on a Hostmonster shared host. I already had SSL configured and the https:// version of the mail server worked perfectly if I typed in the correct https:// url. Trying to find a mod_rewrite configuration that would work redirect http:// connections properly and not give Server Error 500 was not so easy.

There are thousands of pages with ‘how to’ get this to work – but most of them don’t. It’s probably a problem with Apache versions or the setup that Hostmonster has, but I was finally able to devise a solution that works. Place these lines in the .htaccess file of any directory you want to rewrite:

#Hostmonster doesn’t allow +FollowSymLinks, so we use +SymLinksIfOwnerMatch instead.
Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://new.location.com/$1 [R=301,L]

This will check to see if SSL is being used. If it isn’t, then it will redirect it to the new location and provide the client with the “permanently redirected” code (301). This will help other scripts, bookmarks, etc., update themselves auto-magically so they don’t make the same mistake twice.

Cheers.

–JATF

Powered by WordPress