How to: Use mod_rewrite to stop hotlinking in Apache

If you find that people are hotlinking to images on your site, and assuming you have mod_rewrite enabled and working, then just add the following to your root level (i.e. /var/www or such) .htaccess file to cut that crazyness right out:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?the-name-of-your-site\.the-top-level-domain-of-your-site/.*$ [NC,L]
RewriteRule ^.*\.(bmp|tif|gif|jpg|jpe?g|png)$ - [F]

So, for example, on this site, I’m using:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?r3dux\.org/.*$ [NC,L]
RewriteRule ^.*\.(bmp|tif|gif|jpg|jpe?g|png)$ - [F]

I’m just returning a [F] (forbidden) message to the hotlinking web server (so they don’t get an image returned to them), but you can always send them alternate images if you’re feeling vindictive… In fact, there’s lots of neat stuff you can do with mod_rewrite =D

P.S. For a full list of rewrite flags (i.e. [R,L,NC] etc.) and what they do, try this.,

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.