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]
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
In response to the last comment, you can change the last line to instruct the RewriteRule to replace the request with any alternative content that you want to return.
Thanks John….
I will give it a try.
Cheers!