.htaccess hack: remove query strings from URLs

Posted March 18, 2010 by Brian Cray

Reading time: About 2 minutes

Warning: This tutorial is recommended only for people web developers with a working knowledge of .htaccess and dynamic website development. If you’re not in this group, proceed with caution.

A query string is the stuff after the question mark in URLs.

Why remove query strings?

In short: viral potential. Let me explain.

As many of you know, social sharing sites like delicious give URLs a “score,” whether it’s based on # of bookmarks, # of reviews, or whatever.

The important thing is that higher “scores” usually result in increased traffic to your site. For example: enough delicious bookmarks will eventually get you onto delicious.com/popular.

But query strings mess up things. On many social sharing sites, if I share http://briancray.com/ and someone else shares http://briancray.com/?query, the score will be attributed to two unique URLs instead of being recognized as the same URL.

Let’s see what happens when this unique URL problem is applied to delicious bookmarks:

Before the .htaccess hack

Delicious bookmarks are being attributed to two different URLs, even though they are the same page. Result: Not reaching delicious.com/popular despite having sufficient bookmarks

After the .htaccess hack

Query strings are removed from automatically so all bookmarks point to the exact same URL. Result: delicious.com/popular reached, traffic surge.

How to remove your query string with .htaccess

RewriteEngine On
RewriteCond %{QUERY_STRING} !="" #if there is a query string
RewriteCond %{QUERY_STRING} !^p=.* #wordpress users: allow post tempalinks
RewriteCond %{REQUEST_URI} !^/wp-admin.* #wordpress users: don't break admin
RewriteRule ^(.*)$ /$1? [R=301,L] #remove query string

Warnings

  • THIS WILL BREAK ANY FUNCTIONALITY THAT DEPENDS ON QUERY STRINGS
  • WordPress users: Put this code before the line # BEGIN WordPress in .htaccess
  • This will break Google campaign tagging (the benefit out weighs the cost for me)

Conclusion

As most of you know, I don’t recommend writing articles purely to go viral. But if you’re writing good content like Jin Yang, Janko Jovanovic, or Antonio Lupetti, then you deserve all the credit that comes at you.

About the author

Photo of Brian Cray

Brian Cray is a Columbus, Ohio-based web entrepreneur & consultant. View some of Brian’s work in his portfolio and learn how to make kick ass websites by reading his blog.

7 Article comments

Show/add comments

2 Article references from other blogs

Show all references

1789
Previous:
Next: