Using mod_rewrite to prevent hotlinking
May 12th, 2008 | by dave |Hotlinking is the practice of linking to an object (generally an image file) from one site (the donor site) onto another (the linking site). We’re frequently asked by our hosting clients if there is a way to stop people doing this as it’s consuming their bandwidth or server resources. This is easily done with the mod_rewrite rules below.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?opensourcery.co.uk/.*$ [NC]
RewriteRule \.(gif|png|jpe?g|$ - [F]
This will deny requests for any .gif, .png, .jpg or .jpeg file unless the referrer is either www.opensourcery.co.uk or opensourcery.co.uk.
You can substitute the last line for the one below if you wish to redirect people to an alternative image rather than simply denying the requests.
#RewriteRule \.(gif|png|jpe?g|$ img/dontsteal.gif [L,NC]
It’s worth remembering that the referrer header is optional so although almost every modern browser sends this with each request it’s possible that some won’t do meaning these rewrite rules may result in broken images for some users of your site.
Tags: apache, mod_rewrite