Skip to content

Extracting A Query String Parameter With Mod Rewrite


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 . [R=301,L]


This will check the URLs:

and turn it into

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

and turn it into

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 . [R=301,L]

Leave a Reply