Apache Logo

htaccess: Block Visitors by Referer

Well at work a couple week ago, we had one of our affiliates try to use an iframe to serve our site directly through their domain and reap the affiliate benefits. A couple lines of htaccess code fixed that with a little fun mixed in.

Whenever a visitor hits your site, the web server will get a page request with the HTTP_REFERER variable set to the site they reached your site from. So if someone clicks to your site from a Google search, the variable would be set to www.google.com?bunch_of as the HTTP_REFERER variable. We can use htaccess to filter based on this.

htaccess Code

RewriteCond %{HTTP_REFERER} otherdomain\.com [NC]
RewriteRule .* – [F]

Now our web server will return a 403 Forbidden header whenever a requests comes in from the site otherdomain.com. Change “otherdomain” to the offending domain and you’re all set.

The funny thing about this is that the person doing this thinks they’re tricky and smart but in fact has just put their site under your control. If you’re nice you can leave the above htaccess code as is, but if you want to send a message, you can change the RewriteRule to send the offending site anything you want.

RewriteCond %{HTTP_REFERER} otherdomain\.com [NC]
RewriteRule .* block.php [F]

Where block.php can be anything you want. Or if you really want

RewriteCond %{HTTP_REFERER} otherdomain\.com [NC]
RewriteRule .* http://www.anotherdomain.com [F]

Where it will now show a completely different site on their site. This also works for people trying to hotlink your images.

Have fun with it and I’ll leave the creativity up to you =)

Continue Reading