Rewriting URLs

October 1, 2007

In my previous post, I mentioned Apache mod_rewrite lets you take a URL like:
http://yoursite.com/products/index.php?cat=software&item=Photoshop
and convert it to something like:
http://yoursite.com/products/software/Photoshop

There are two main benefits to formatting URLs the second way.

  • it’s easier for visitors to read.
  • it’s easier for Google to index.

You also gain a number of positive side effects, one of which is the ability to keep your variables hidden. Basically, the only reason not to rewrite URLs is the added effort required to do it. But, what if the added effort really wasn’t that significant?

It’s not.

First, let’s assume my earlier mention of Apache already turned off anyone not using it (if your rewrite engine doesn’t match mine, I’m no good to you.) Let’s also assume those who already know how to do this (and probably better than I) already got bored and moved on.

Okay, now if you’re still with me, all you need to do is create an .htaccess file in the directory you’re looking to rewrite (/products/ in my case) with the following lines:

RewriteEngine on

#Rewrite for software categories
RewriteRule ^([^/\.]*)/([^/\.]*)/?$ index.php?cat=$1&item=$2 [L]

Variables work the same, queries work the same, etc. It’s a lot like magic.

That’s it friends. Hi5.

Speeding

September 30, 2007

Last month, I dropped a few posts about url optimization. The reason for three posts was simple - I couldn’t get it out of my head.

With our rate of development, it’s easy to get caught up in efficiencies and speed past the question: what’s the best way to do this? In this case, rewriting URLs is the best way, but passing the query string was the quickest.

I’ve been trying to pay more attention to this since we got called out a few years ago for another quick practice: bad HTML code. Two versions back, we launched our own site in non-standards-compliant form. Didn’t even think about it, just coded it quick and launched. The next day when the site caught some attention, a commenter pointed out our (my) nested tables.

We had the site re-coded that day, but it still bugs me that someone else had to catch us (me) speeding before I caught it myself.

More recently, we’ve been called out on a few Truemors hacks. Most of these were rants on the process vs the mechanism, but there have been a few that I half expect to be followed by a consulting bill.

I’m finding criticism to be a hell of a resource.

We didn’t actually get called out on URL rewrites, but I’m sure it was only a matter of time. We’ve since rolled it into just about everything we do, and like cutting over to good code (the kind that validates) or optimizing open-source apps, we’re finding that it’s exceptionally easy to do.

I’ll follow this with a post showing exactly how easy it is to rewrite URLs. If I can save just one person the emotional distress I suffered by being made fun of by a mean high school kid, it’s worth it.