Using .htaccess to block referrer spam

Lately referrer spam became a great annoyance for the webmasters. If you are not sure what referrer spam is you may wish to check this article: http://en.wikipedia.org/wiki/Referrer_spam

To block these spam referrers you need the following lines in your .htaccess file:

# set the spam_ref variable
SetEnvIfNoCase Referer "^http://(www.)?some-spammer.com" spam_ref=1

SetEnvIfNoCase Referer "^http://(www.)?other-spammer.com" spam_ref=1

SetEnvIfNoCase Referer "^casino-poker" spam_ref=1

# block all referres that have spam_ref set
<FilesMatch "(.*)">
Order Allow,Deny
Allow from all
Deny from env=spam_ref
</FilesMatch>

The first lines “setenvifnocase” assign a span_ref environment variable. Then we deny all access to such referrers in the FilesMatch clause.

You can also use wildcards with the above .htaccess directives to match a variety of hosts. For example, you can use

SetEnvIfNoCase Referer "*some_word*" spam_ref=1

to match all referrers that contain the word ‘some_word’.

For example you can ban visits from referral sites that contain in their domains words like: phentermine, viagra, cialis, shemale, porn, nude, celebrity, etc.