Remove a Query String From a URL with Mod_Rewrite

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 an URL with a query string into an URL without?

 

Remove the querystring from an URL

 

We were redesigning and an old site that had been hacked and had some spurious content inserted. Subsequently, the site ended up with tonnes 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 substitution 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 a 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? Drop me an email, I am sure we can help!

 

Facebook
Twitter
LinkedIn
Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *

Free Digital Marketing Review

Book a call with Marcus Miller to learn how to generate more traffic, leads and sales.

1. Review your current marketing
2. Identify your key opportunities
3. How to improve results & cut costs!

Put over 20 years of marketing experience to work for your business today.