12 June 2008 ~ 0 Comments

Redirects and mod_rewrite

I don’t write a lot about tech stuff in this space, but I do have one rule: if something takes longer than it should (or that I’d like) and involves much experimentation, I’ll share.

I’ve been using Google Webmaster Tools to track site statistics. Surprisingly, there were many incoming links to invalid URLs, all to my old images:

From my experience with WordPress I knew that URL rewriting could fix this. I want to replace “photos” with “galleries” and I’m all set. Seemed simple enough!

Tick tock… 12:30am turned to 1:30am… turned to 3am. In the world of technology, mod_rewrite and regular expressions are just about the two last things you’d want to mess with after midnight :)

The first part is easy – match all URLs that aren’t files or directories (in case these documents do actually exist) and contain the word “photos”:

                RewriteCond %{REQUEST_FILENAME} !-f
                RewriteCond %{REQUEST_FILENAME} !-d
                RewriteCond %{REQUEST_FILENAME} photos

I could have a blog post containing the word “photos” (I don’t) but I didn’t worry about that.

Next, through the use of a RewriteRule, I need to figure out how to turn this:

http://www.allaboutbalance.com/photos/creatures/slides/Rallying%20Cry.html

Into this:

http://www.allaboutbalance.com/galleries/creatures/slides/Rallying%20Cry.html

Not only that, I want the search engine crawlers to record it as a permanent redirect (HTTP 301) and stop perpetuating these old URLs.

                RewriteRule  photos(.*) /galleries$1 [R=301,L]

The tricky bits are the $1 and [flags]. The $1 refers back to the Pattern, photos(.*), and basically writes a new URL that starts with /galleries and appends everything that matches after the word photos.

The [flags] tell the browser this was an HTTP 301 Permanent Redirect, and that for the preceding conditions, this should be the Last rule (i.e. stop processing).

References:

Apache mod_rewrite Reference @ apache.org
Regular Expressions Tutorial @ regular-expressions.info

Leave a Reply