selective .htaccess hotlink protection

description:

due to an increasing number of sites using images, stylesheets and flash movies directly from my server, today i implemented an .htaccess based "hotlink protection" scheme.

the theory is simple, and there are a lot of good examples out there: using Apache's mod_rewrite module, check the referrer of any request; if it appears that another external site is linking directly to a certain type of file, fail the request through a 403 status code (or do something witty like serving an alternative "stop stealing my bandwidth" type image).

the basic code for a draconian hotlink protection would look something like this:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://www\.splintered\.co\.uk/
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpe?g|gif|bmp|png|css|mov|swf|dcr)$ - [F]

if the referrer is not the address of your site, and it's not empty, fail any request ending with any of the listed file extensions.

there are, however, situations in which you'd want to allow a select number of external sites to link directly to your files. a good example would be my "special effects" entry to the csszengarden, door to my garden (advanced). here, a stylesheet hosted on my site is effectively being hotlinked from a page on a completely separate domain. the restrictive rewrite rule would simply block this request. similarly, the above code would prevent me from ever including images, or even linking to images or certain types of files, from some of the online forums i frequent on a regular basis.

so, how to allow certain sites to hotlink, while keeping any other unwanted ones out? the solution is deceptively simple, thanks to a fairly straightforward regular experssion in the rewrite condition pattern (which, additionally, takes into account the possibility that some domains may or may not use the www prefix, and may end in .co.uk, .com or .org):

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?(splintered|csszengarden|accessifyforum|sitepoint|archive)(\.co\.uk|\.com|\.org)/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpe?g|gif|bmp|png|css|mov|swf|dcr)$ - [F]

completed:
03/09/2004