Wayne State Web Team

Wayne State University Web Team Blog

Redirection with ModRewrite and GET variables

Yesterday I started working on the redirect in the .htaccess for the homepage. The quick links on the homepage are redirected using ModRewrite then pushed through a php file that logs the action. This lets us monitor their usage so we can make sure the best possible links are available in this drop down. Here's the code we were using in the .htaccess:

RewriteRule ^r/(.+)$ http://wayne.edu/r.php?url=$1

It was working well with normal URLs but when a URL was passed that had a query string, that query string was being truncated leaving the forwarding php with a URL that didn't have a query string which then forwarded to the wrong location.After looking deeper into the options available with ModRewrite I found the [QSA] flag. This appends the query string back onto the URL when forwarding, which allowed me to modify the php file that was managing the forwarding so it could reattach the missing query string onto the end of the URL. So now the quick links will forward properly, even with complicated URLs.Here's that same RewriteRule with the flag:

RewriteRule ^r/(.+)$ http://wayne.edu/r.php?url=$1 [QSA]

The PHP file gained this code which reattaches the query string back onto the end of the URL being passed in.

foreach($_GET as $key => $item){

if($key != 'url'){

$pieces[] = $key . ($item != '' ? '=' . $item : '');

}

}

$url = $_GET['url'];

if(sizeof($pieces) > 0){

$url .= '?' . implode('&', $pieces);

}