Image Hotlinking Prevention with .htaccess
I'm designing some banners and buttons for Ubuntu advocacy. I have no problem with giving the images away [indeed this is why I made them,] however I really can't afford to host them. So before I post them to this site I wanted to ensure that I had some hotlink protection in place.
To accomplish this I've created a new directory under my site's default "images" directory and protected it from hotlinking with an Apache .htaccess file. For future reference here are the contents of the .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+.)?example.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*.(jpe?g|gif|bmp|png)$ ../hotlink.gif [L]
The first line of the above code turns on the mod_rewrite engine in Apache. A requirement for the rewrite commands.
The second line matches any requests from the URL example.com [change this to suit your requirements]. The [NC] code means "No Case", meaning match the URL regardless of case.
The third line allows empty referrals.
Finally, the last line matches any files ending with the extension jpeg, jpg, gif, bmp, or png. This is then replaced by the hotlink.gif file [see below] residing in the above images directory.

If you need to allow more domains to hotlink to your images you can simply duplicate line two. See the example below:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+.)?example.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+.)?another-example.net/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+.)?one-more-example.org/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*.(jpe?g|gif|bmp|png)$ ../hotlink.gif [L]
Add Your Comment
Use the form below to add your comment. Markdown syntax is available. Note, comments are moderated by me for spam filtering. Alternatively, feel free to contact me privately.