Stripping out query string with mod_rewrite
11 Mar 2008
We ran into a weird problem at work today. We use CodeIgniter for our web site, and due to some configuration (which, frankly, astounded me when I heard about it), we generate 404s on pages if we get unknown query string parameters. We're testing integration with other systems, and some of them automatically add additional query string parameters when returning to our pages.
A solution was mooted that involved using a standalone PHP file that used file_get_contents with an HTTP URL to strip out the query string parameters. Which is not the solution we want when we're trying to make sure we don't have performance-restricting aspects to our service — it would double up HTTP requests.
Normally, mod_rewrite doesn't interact with query strings — it maps the incoming resource to another resource, and query string parameters aren't part of the resource. But hidden in the mod_rewrite documentation is this:
Modifying the Query String
By default, the query string is passed through unchanged. You can, however, create URLs in the substitution string containing a query string part. Simply use a question mark inside the substitution string to indicate that the following text should be re-injected into the query string. When you want to erase an existing query string, end the substitution string with just a question mark. To combine new and old query strings, use the [QSA] flag.
In our case, we just added a question mark to the right-hand-side of the rewrite rule, and we saved ourself an HTTP request.
5 Responses
Charl van Niekerk — March 11, 2008 at 01:06 PM.
Neil Blakey-Milner — March 11, 2008 at 05:04 PM.
RewriteRule /foo.php /otherthing?
So, we were getting calls to /foo.php?asdf=123&qwer=zxcv and we converted that (without the client knowing about it) into a call to /otherthing without a query string at all.
Charl van Niekerk — March 12, 2008 at 05:26 PM.
Neil Blakey-Milner — March 12, 2008 at 06:07 PM.
Charl van Niekerk — March 14, 2008 at 07:20 PM.
Have your say