Preventing hotlinking from certain domains

Tags: howtos, linux

Published on
« Previous post: Frak, an interpreter for the brainf*ck … — Next post: constexpr and floating point rounding … »

I recently discovered a new plague on the internet—“Scraper Sites” and their brethren. While I can live with the fact that their bots are actively marketing my “valuable content” (cue laughter) as their own, I draw the line at stealing my traffic. Although the amount they steal by hotlinking my images is comparatively small, I still consider it a matter of principle to fight these sites. Foremost, the internet is a place for information. By displaying publicly-available information in a very confusing and haphazard way (most of the “people search engines” out there do not even attempt to check the names for correctness), they only confuse people.

I will not let this stand, so I devised a way of blacklisting these sites and serving them different content instead of the images they attempted to access. Assuming you have an Apache webserver with mod_rewrite installed, place the following in either your .htaccess file or one of the vhost configuration files in /etc/apache2/sites-available:

<IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteCond %{REQUEST_FILENAME} !hotlinking\.png$
        RewriteCond %{HTTP_REFERER} ^http://(www\.)?.*(-|.)?example\.org.*$ [NC,OR]
        RewriteCond %{HTTP_REFERER} ^http://(www\.)?.*(-|.)?example\.com.*$ [NC]
        RewriteRule \.(gif|jpg|jpeg|png)$ /images/hotlinking.png [R,L]
</IfModule>

This snippet rewrites any image requests that come from a subdomain of example.org or example.com to the file in /images/hotlinking.png. The first condition ensures that the rewriting does not pertain to the hotlinking.png itself. You do not necessarily need this condition if all your images are placed in a single folder and you place the hotlinking.png one outside of it.

Note that I only explicitly deny hotlinking to those who want to make a quick buck. I have absolutely no problem with other people hotlinking my content—I consider this a mark of honour and will gladly take their additional traffic. Hence, I cannot wholeheartedly recommend that you block any referrer that does not come from your own domain.

Happy internetting.