Blocking Referrer Links Through htaccess

In recent months, I’ve noticed a lot of incoming links from undesirable sites. I suppose any traffic is good traffic, but I would prefer to not have my content found through these spam sites. While I can’t prevent other sites from including a link to my site or copying my content, I can prevent them from directly linking to my images (hotlinking) or having users directed to my site from these other sites. With a little regular expression magic and my htaccess file, I can force an error to be returned or redirect the links somewhere else.

The first line instructs Apache to enable the runtime rewriting engine which allows it to process the subsequent rewrite conditions and rules.

This first section will block any requests where the originating site or referral site matches the established rewrite conditions. In this example, the conditions block requests from any site in the .cc, .eu and .ru top-level domains. The second condition line blocks requests from specific domains. The RewriteRule forces a 403 forbidden header to be returned to the originator.

This next section handles image hotlinking by redirecting any requests for .jpg, .jpeg, .gif or .png files where the originating request is not from my site. The RewriteRule forces a 403 forbidden header to be returned to the originator.

With everything together, the htaccess file should include the following in addition to any site specific htaccess code:

8 thoughts on “Blocking Referrer Links Through htaccess”

  1. Great post. I am not versed in apache but wonder how you would block a domain referral and then redirect it to a specific page. I am working in wordpress and have access to the .htaccess.

    Thanks for your help,
    Bill

    Reply
  2. In response to the last comment, you can change the last line to instruct the RewriteRule to replace the request with any alternate content that you want to return.

    Reply
  3. I have been searching how to block referrer to the specific domain tld .ru, and your post really help me. Frankly, my site has too many referer comes from .ru, and very annoying.
    Thank you very much John. I’ll come back soon I have another problem…. I hope you do not mind to share your knowledge.
    Cheers.

    Reply
  4. OK, thanks for sharing how to block .ru domains. How can I put in an exception for for example google dot ru or yandex dot ru? If I am not mistaken you’re blocking those as well.

    Something like this: RewriteCond %{HTTP_REFERER} !(google|yandex)\.(ru|ua)/ [NC] ?

    Reply
  5. I think that would work. I haven’t tested this, but I would expect it to look something like the following:

    Reply
  6. Hello,
    This is very useful htaccess code. From last few days, I was very annoyed from .xyz TLD domain.
    Finally, I found this awesome guide. Thanks John.

    Reply

Leave a Comment