Search Engine Friendly URLs with mod_rewrite

By · Published · apache, rewrite

Tags: apache, mod_rewrite, rewrite

By now, I'm sure we all know about search engine friendly (SEF) URLs - that is, URLs that are able to be traversed by a search spider. Spiders don't like to see a bunch of stuff on the query string (file.html?blah=foo), but do like standard URL patterns like /file/foo.html. Not to mention that it's a lot easier to read. But what happens when you need to do something more complicated - say, rewrite using different types of conditions with optional arguments?

Say, for instance, I have a script that takes arguments like this:


And I want to rewrite it to look like this


In this case, the view argument is optional and could relate to any number of unique cases, such as internal viewing or refcode tracking, for instance. Well, your first thought might be something like this:

RewriteCond %{REQUEST_URI} ^\file\/\d+\.html [OR]
RewriteCond %{REQUEST_URI} ^\/file\/\d+\.html(.*)
RewriteRule ^\/file\/(\d+)\.html(.*) /file.php?id=$1&$2 [L]`

But it doesn't work. This is because the query string isn't part of the URI available for the rule to match. But, mod_rewrite, being the cool Swiss Army knife it is, lets you get around this by back referencing to the condition. Using the % operator instead of the $ allows you to reference parentesized expressions in the condition, like so:

RewriteCond %{REQUEST_URI} ^\/file\/\d+\.html
RewriteCond %{QUERY_STRING} (.+)
RewriteRule ^\/file\/(\d+)\.html?(.*) /file/file.php?id=$1&%1 [L]
RewriteCond %{REQUEST_URI} ^\/file\/\d+\.html
RewriteRule ^\/file\/(\d+)\.html /file/file.php?id=$1 [L]`

It's described here in the docs. I thought this was a pretty cool solution to a problem that had been vexing me.

( Comments )

Did something I wrote help you out?

That's great! I don't earn any money from this site - I run no ads, sell no products and participate in no affiliate programs. I do this solely because it's fun; I enjoy writing and sharing what I learn.

All the same, if you found this article helpful and want to show your appreciation, here's my wishlist.

Related Posts

Automatically Provisioning Polycom Phones

Multiple Calibre Servers under Mac OS X

comments powered by Disqus