Web : Prevent image hot linking to your site

By | January 10, 2012

This article is about stopping theses sites who hot link your images, steal them and your bandwidth! I assume you are running Apache as Web server and have some basic knowledge of httpd.conf, htaccess and rewrite rules.

You have two choice, either put the rules directly inside your httpd.conf vhost or inside an Apache configuration file (well known as .htaccess). If you use the httpd.conf way, you can ignore the first step.

First, make sure your vhost is allowing htaccess usage (in httpd.conf) :

AccessFileName .htaccess
<Directory "/path/to/vhost">
AllowOverride All
Options SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>

 

Now, add theses rewrite rules into your config file (httpd.conf or htaccess) :

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?domain.tld [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ http://public.domain.tld/images/hotlinking_denied.jpg [NC,R,L]

Ok, let’s explain this a little bit… the following line contain the URL who is authorized to call images (your own site must be listed! – replace “domain.tld” with your own domain). You may add as many allowed URL you want, simply duplicate the line and domain.

RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?domain.tld [NC]

The last line contain the image to return to theses stealers… their site will show this image instead of the one they tried to link (again, replace with your own URL/path) :

RewriteRule \.(jpg|jpeg|png|gif)$ http://public.domain.tld/images/hotlinking_denied.jpg [NC,R,L]

*Make sure the image you want to display is not contained into the same URL you are trying to protect. Infinite loop is expected!