RegEx URL Rewrites

Writen by: Hank Wethington

Posted on 14 May 2009

*** DORK ALERT ***


I was tasked yesterday with creating a rewrite rule in apache to handle a URI query that need to change for a site. This ended up being an exercise where my head was bloodied from banging it against my desk. Of course it didn’t help any that the client that needed this gave us hardly any time to accomplish it. Read on for more info.

Here’s what the original URL looked like:

the new URL should look like:

OK, so the first part is pretty easy.

RewriteRule ^/locator/person.aspx(.*) /locator/cool_person.html$1

That would work if the blahId was used instead of just id and if I didn’t need to add &people=1 to the end. After a little playing around, I broke up the URI query and created a QUERY_STRING Condition, then created the rule:
RewriteCond %{QUERY_STRING}    ([^=]*)=(.*)
RewriteRule (.*) $1?%2
RewriteRule ^/locator/person.aspx$  /locator/cool_person.html?id=%{QUERY_STRING}&people=1

Of course, my plan was to break arpart the URI into two pieces, but you have to be really careful with RegEx… it can be really aggressive. My testing worked. The rewrite did exactly as expected and I sent out an email to my work team beaming with pride over creative solution…

Then it went live, and nothing worked as expected. Due to the aggressive nature of my rewrite condition along with the proceeding rewrite rule, the next rule was catching the new URL coming through along with the  URI query and reprocssing it. Of course, I wasn’t expecting it to. My testing environment, since it wasn’t even remotely similar to the production one, didn’t catch this problem. The final solution was to not be so greedy with the condition. My coworker came up with the fix while I was out:

RewriteCond %{REQUEST_URI}    ^/locator/person.aspx$
RewriteCond %{QUERY_STRING}   ^blahId=([0-9]*$)
RewriteRule ^/locator/person.aspx$ /locator/cool_person.html?id=%1&doctor=1

As the rule was much more selective, it didn’t screw with the rest of the site. By only looking at the single query string we wanted, we get the desired result set in %1 without rewriting the whole URL just to be reprocessed by the next rewrite rule.

I hope this helps someone out there, as my original fix was assisted by a good google search.

No responses yet. You could be the first!

Leave a Response

You must be logged in to post a comment.

Recent Posts

Tag Cloud

5k art basketball beer blogging C25k candy Chruch coffee cycling drama Family Food funny God hills injury IT Kids LEVEL media Merrell motorcycle music Oktoberfest photo pictures porter run running SLO social sports stout Thoughts trails training triathlon vacation VftR video Weight weight loss work youtube


Wethington Family Blog is proudly powered by WordPress and the SubtleFlux theme.

Copyright © Wethington Family Blog