Prevent image hotlinking with Apache and htaccess

Posted by Danny Herran on Aug 9, 2010 in Backend | No comments

Question of the million dollars. Those annoying image hot-linkers, eating our bandwidth, our food, our… nevermind. Anyway, if you want to give them hell and stop this behaviour, add the following to your .htaccess file (remember to edit your domain name):

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://your-server-ip/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^*$     [NC]
RewriteCond %{HTTP_REFERER} !^*$  [NC]
RewriteRule .*.(gif|GIF|jpg|JPG|png|PNG)$ - [F]

Bonus!: In the third line, you can optionally write your server IP for an extra layer of security. If you don’t know your server’s IP, just open an MS-DOS console (if you’re on Windows) or a Linux console and ping your domain. ie. “ping”, would return which is my server IP.