stop hotlinking with htaccess

While browsing through the web, you find a very interesting image for your site. There are 2 ways in which you can add it to your own site (assuming it is a free image) – download the image to your local computer and upload it to your site or add a direct link to that image on your site. The 2nd method is known as hotlinking. It is a method wherein you take images or other files from websites and embed it onto your own site. Whenever a page that includes such an image is loaded, the image is downloaded from the original site. A hotlinked image’s HTTP code would typically look like –

<img src=””>

If the person who owns the media file that you want to embed on your site give you permission to hotlink, then all is well. Sadly, this is not usually the case. If you don’t have required permission, remote linking to any media file is equivalent to theft. Every time that image is downloaded from the original site, we steal precious bandwidth from them.

Next time you see a sudden spike in your bandwidth usage, don’t forget to check your logs for image downloads. It could be a result of one of your images being hotlinked. Detecting hotlinking is not as easy as preventing it. So why wait till you land a hefty bill to swing into action when you can easily stop hotlinking with htaccess. All you’ve to is add the following rules –

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ badimage [NC,R,L]

Whenever someone tries to hotlink to any image on your site, a badimage will be displayed. You can also test these rules once you enable them by using one of the htaccess test tools. Lastly, don’t forget to backup your htaccess file before making any additions to it.

Share via
Copy link