Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Blocking users/ sites by referrer

Note: This portion of tutorial written by JavaScript Kit

Blocking users or sites that originate from a particular domain is another useful trick of .htaccess. Lets say you check your logs one day, and see tons of referrals from a particular site, yet upon inspection you can't find a single visible link to your site on theirs. The referral isn't a "legitimate" one, with the site most likely hot linking to certain files on your site such as images, .css files, or files you can't even make out. Remember, your logs will generate a referrer entry for any kind of reference to your site that has a traceable origin.

Before I get to the code itself, it's important to note that blocking access by referrer in .htaccess requires the help of the Apache module mod_rewrite to make out the referrer first. This module is installed by default on most servers (ask your host if you're not sure). So, to deny access all traffic that originate from a particular domain (referrers) to your site, use the following code:

Block traffic from a single referrer:

RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} badsite\.com [NC]
RewriteRule .* - [F]

Block traffic from multiple referrers

RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} badsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherbadsite\.com
RewriteRule .* - [F]

In the "single referrer" case above, "badsite\.com" is the domain you wish to block. Note the backslash proceeding the period (".") to actually donate a period, as in Regular Expressions, a period donates any character, which is not what we want. The flag "[NC]" is added to the end of the domain to make it case insensitive, so whether the domain is "badsite.com", "Badsite.com" etc, however bad it gets, it gets blocked. Finally, the last line in the .htaccess file specifies that the action to take when a match is found is to fail the request, meaning the referrer traffic will hit a 403 Forbidden error. The only difference between blocking a single referrer and multiple referrers is the modified [NC, OR] flag in the later case to every domain but the last.

Now, you may have noticed the line "Options +FollowSymlinks" above, which is commented. Uncomment this line if your server isn't configured with FollowSymLinks in its <directory> section in httpd.conf, and you get a 500 Internal Server error when using the code above as is.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.