Mr Kirkland

Url rewrite for query strings

Bookmark and Share


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

2 Responses to “Url rewrite for query strings”


  1. 1 Boz Jun 12th, 2007 at 9:07 am

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

  2. 2 Mr Kirkland Jun 12th, 2007 at 9:12 am

    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




Timezone

  • JST: 2008-07-06 05:46
  • BST: 2008-07-05 21:46
  • PDT: 2008-07-05 13:46