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.

RewriteEngine on

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.

RewriteCond %{HTTP_REFERER} ^http(s)?://(.*)?\.(cc|eu|ru)(/.*)?$ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http(s)?://(.*\.)?(site1\.com|site2\.com)(/.*)?$ [NC]
RewriteRule .* – [F]

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.

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(.*\.)?mysite\.com(/.*)?$ [NC]
RewriteRule \.(jpe?g|gif|png)$ - [NC,F]

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

RewriteEngine on
 
RewriteCond %{HTTP_REFERER} ^http(s)?://(.*)?\.(cc|eu|ru)(/.*)?$ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http(s)?://(.*\.)?(site1\.com|site2\.com)(/.*)?$ [NC]
RewriteRule .* – [F]
 
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(.*\.)?mysite\.com(/.*)?$ [NC]
RewriteRule \.(jpe?g|gif|png)$ - [NC,F]

About John Dalesandro

My name is John Dalesandro and I am a software engineer based in New Jersey. My experience covers all aspects of the software development life cycle with a primary focus on enterprise web applications.