Prevent specific sites from hotlinking using .htaccess
Posted in SEO on October 10th, 2009 by Ilir Fekaj – Be the first to commentWhen I first created AvatarsDB site, my idea was to allow people to simply link to individual avatar images without need to search for image hosts or download images to their computers. However, after some time there were people who started to abuse this service. I had cases when people built entire sites and blogs just by linking to thousands of images from my site. No need to mention that this wasted gigabytes of my bandwidth and sent hundreds of thousands of useless request to my server without providing even single link back. I wanted some solution which will allow legitimate users to use this service and block bandwidth leeching.
Solution is very simple and it involves editing your .htaccess file and creating replacement image which you will show to visitors of offending site. This can also bring some traffic to you if you put name or address of your site. Simply put this code in directory where you keep your images or in root if you wish to prevent hotlinking in all directories:
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http://(.+\.)?evilhotlinker\.net/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(.+\.)?leecher\.com/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(.+\.)?annoyance\.net/ [NC]
RewriteRule .*\.(jpg|gif|bmp|png)$ images/nohotlink.gif [L]
You can put as many sites in this list as you like, just make sure lines before last one on the list end with [NC,OR] which tells Apache to continue matching. If you want to save bandwidth, you can also send error 403 Forbidden by editing last line to this:
RewriteRule .*\.(jpg|gif|bmp|png)$ - [F]
You can also block all hotlinking and allow only your site:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://yourdomain.com.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.yourdomain.com.*$ [NC]
RewriteRule .*\.(jpg|gif|bmp|png)$ images/nohotlink.gif [L]
You should put all these codes before you do any URL rewriting or they might not work. When you’re done editing, make sure you upload it in text mode or it also may not work.