Wednesday, March 10, 2010

.htaccess and RewriteRule

This had me puzzled for a little while, because it was so non-intuitive.

Wolfram's blog was moving from FTP upload to being hosted by Blogger. He wanted redirects on his old Blog Website at http://www.kritzelecke.de/blog/leoslifelog.html for all html pages, while still hosting the images in their old location, since the Blogger migration tool doesn't move them. So we need a redirect that only covers html pages, but not the images, and only for the path that used to host the blog.

My intuitive solution for this was to stick the following into a .htaccess file in the /blog directory:

RewriteEngine On 
RewriteRule ^/blog/(.+)\.html http://blog.kritzelecke.de/$1.html [R=permanent,L]

To my surprise this didn't seem to do anything. Not having access to error logs didn't help.

In the end I recreated the problem on a local Apache instance. At first I thought the .htaccess file gets ignored by Apache. After some searching and eventually reading the docs for mod_rewrite in their entirety, I stumbled over this comment in http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritebase :
As you will see below, RewriteRule can be used in per-directory config files (.htaccess). In such a case, it will act locally, stripping the local directory prefix before processing, and applying rewrite rules only to the remainder.
So the solution was to simply remove /blog from the RewriteRule, since I don't really about path processing for external redirects, and (as icing on the cake) add a specific redirect for the top page.

RewriteEngine On
RewriteRule ^/leoslifelog.html http://blog.kritzelecke.de/ [R=permanent,L] 
RewriteRule ^/blog/(.+)\.html http://blog.kritzelecke.de/$1.html [R=permanent,L]


Of course, this all might be obvious for all you Apache jockeys out there, but I learned something new.


Now on to another experiment whether I can restrict access to parts of my site based on a cookie, with a redirect to a registration page if the cookie is not present while keeping most of the site static html. 

1 comment:

Leo said...

And it works brilliantly!
Thanks again!