Nearly all of the mod_rewrite and .htaccess tutorials on the internet are focussed on using the undoubted power of mod_rewrite to rewrite messy, variable heavy urls (page.php?id=1&title=hello&name=world) into cute, fluffy urls without the messy query string. This is fine but... what about if you want to do this in reverse just rewrite a URL with a query string into a URL without?
Remove the querystring from a URL
We were redesigning and old site that had been hacked and had some spurious content inserted. Subsequently the site ended up with tons of random inbound links for a bunch of weird URLs pointing at the site. The format was essentially a page name and variable something like the this:
page.php?variable=hello-this-is-an-example
page.php?variable=there-were-hundreds-of-these
page.php?variable=seriously-hundreds
page.php?variable=they-had-to-go
Rewrite to new page minus the get string
We wanted to simply rewrite all of these pages with a single rule to the site root - /. Now, we had used mod rewrite a bunch of times, easy we figured, yeah? Well, like anything with mod rewrite it was easy, but we missed something that caused us untold grief whilst searching big google for an answer.
So, our initial rewrite rule was simple, just rewrite the bad page and all possible querystrings to the site root, something like:
rewriterule ^page\.php$ / [R=301,L]
Only problem with this was that we ended up with the original query string left on the end of the rewritten page so...
page.php?variable=please-go-away
was rewritten to:
/?variable=please-go-away
So, we tried a bunch of complicated and painful approaches to what was seemingly a simple problem but could find no simple answer until we tried the following, see if you can spot what is different to the original rule.
rewriterule ^page\.php$ /? [R=301,L]
Spot it? All we did was add a question mark at the end of the subsitution so / became /?. I was aware of the use of ? in the patterns to be rewritten but had not come across it in this context. So, this, little known feature, a single question mark for seemingly simple job took up a whole bunch of time. Hopefully, this post may save you some of that time!
Marcus Miller
Got any questions
Got a website problem? Need some help with your mod rewrite or any other aspect of your site? This e-mail address is being protected from spambots. You need JavaScript enabled to view it , I am sure we can help!
