Skip to content

Url rewrite for query strings

by Mr Kirkland on June 11th, 2007


Url Rewriting

We all know and repsect the voodoo that is apache mod_rewrite, the superb apache mod that allows one to redirect/rewite urls, silently redirecting nice SEO friendly URLS to
standard query string types e.g.:
http://www.coolsite.com/news/coolstuff/new-url-rewriting-mod/ -> http://www.coolsite.com/?pageid=123871&catid=2432

Moving Pages

One handy use of mod rewrite is when you re-organise your sites url structure, it’s ability create redirects for all the old urls with regular expressions can be a real life saver as all your previous incoming links may end up with ghastly 404 page not found messages. This is especially useful when simple 301 Redirects aren’t powefull enough

One Caveat however, is that mod_rewrite can’t rewrite query strings with the normal RewriteRule. for example:
Works:

RewriteEngine On
RewriteRule ^cakes/ /puddings/cakes/

Doesn’t work

RewriteEngine On
RewriteRule ^cakes/?cakeid=12 /puddings/cakes/sponge/

Instead, one has to use the RewriteCond to catch the Query String:

RewriteEngine On
RewriteCond %{QUERY_STRING} cakeid=12
RewriteRule ^cakes/ /puddings/cakes/sponge/

So in detail, to redirect:
http://www.mysite.com/url/path/?some=query&other=queries&etc
to

http://www.mysite.com/new_url/


RewriteEngine On
RewriteCond %{QUERY_STRING} some=query&other=queries&etc
RewriteRule ^url/path/ /new_url/

Ref:
http://httpd.apache.org/docs/1.3/misc/rewriteguide.html

From → webmastering

2 Comments
  1. Boz permalink

    don’t forget [L]at the end (Last rule)

  2. Mr Kirkland permalink

    don’t forget [L]at the end (Last rule)

    That’s a good point sir!
    Rule becomes
    RewriteRule ^url/path/ /new_url/ [L]

    I’d also suggest us of a 301 redirect with [R=301]:

    Rule becomes:
    RewriteRule ^url/path/ /new_url/ [L,R=301]

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS