Brian Cray ··· Home > Blog > Analytics > .htaccess hack: remove query strings from URLs

.htaccess hack: remove query strings from URLs

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

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.