Skip to content
 

Extracting A Query String Parameter With Mod Rewrite

Background

I was recently working on a website that was being modernized and we had to redirect the old site to the new site.  This shows the solution along with an explanation. This is targeted to those familiar with mod-rewrite.

Extracting a single parameter

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteBase /

  RewriteCond %{REQUEST_URI} ^/oldpage\/oldfile\.php [NC]
  RewriteCond %{QUERY_STRING} ^.*[&]?id=(\d+).*$ [NC]
  RewriteRule . http://newsite.com/newpage/%1/? [R=301,L]

</IfModule>

This will check the URLs:

http://oldsite.com/oldpage/oldfile.php?id=5

http://oldsite.com/oldpage/oldfile.php?ignored=123&id=5

and turn it into

http://newsite.com/newpage/5/

A breakdown of the query string:

^ Asserts position at the beginning of a string
.* Read any and all characters up to the next match
[?]? Match a ? zero to 1 times (allows the parameter to be listed after other parameters)
id=(\d+) Match literally “id=” then read all (at least 1) decimal numbers into a back reference.  \w instead of \d will capture all standard letters and digits
.* Match the rest of the line
$ Assert the end of the line

The question mark at the end of the rewrite rule specifies that the old query string will not be appended to the new URL.  The [NC] at the end of each of the RewriteCond lines specifies that the match will be case insensitive (id=1,Id=1).   [R=301, L] means the redirect will be a type 301 (permanent) and that to stop processing rewrite rules (L is for last).

Extracting Multiple Parameters

Multiple parameters can only be extracted if you know the order they are listed in the URI.  The following example would extract ‘id’ as a number and ‘category’ as a word. The order must be accurate. The following would match

http://oldsite.com/oldpage/oldfile.php?id=123&category=mycategory

http://oldsite.com/oldpage/oldfile.php?id=123&ignored=456&category=mycategory

http://oldsite.com/oldpage/oldfile.php?ignored1=abc&id=123&ignored2=456&category=mycategory

and turn it into

http://newsite.com/mycategory/123/

Notice the order of the capture groups, ‘id’ is capture into %1 and ‘category’ into %2.

  RewriteCond %{REQUEST_URI} ^/oldpage\/oldfile\.php [NC]
  RewriteCond %{QUERY_STRING} ^.*[&]?id=(\d+).*&category=(\w+).*$ [NC]
  RewriteRule . http://newsite.com/%2/%1/? [R=301,L]

Leave a Reply