Smarter Way To Prevent Image Hotlinking with .htaccess

Have you noticed someone stealing your images, directly taking the URL and display on their websites without your permission? This is what we call image hotlinking. It is bad, as it not only stealing our images, it also take advantage of our bandwidths. Because it’s called directly from our server, every time the images are loaded on their webside it cost us bandwidths. Controlling via .htaccess is one of the most efficient way to prevent image hotlinking.

And by smarter way, we mean giving the webmaster more control on the .htaccess in terms of:

  • what sites to block
  • what sites to allow
  • allow/deny blank referrers
  • display custom images detecting image hotlinking
  • files to protect

Step 1 – Create .htaccess

If you’re currently not using any .htaccess in your web account you should be creating one. Open up notepad, save it as .htaccess without any extension behind. For those who already have an existing .htaccess file, download it to your local computer as we’ll be doing some editing in Step 2.

Step 2 – .htaccess hotlinking code

Paste this following code into your .htaccess.

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

Explanation

Line 2 – Allow blank referrers (recommended).

 
RewriteCond %{HTTP_REFERER} !^$

Some users surf under firewall and thus they are not providing any referrers information. Disallowing blank referrers will means blocking them from accessing these images. However if you want to block blank referrers, just delete line 2.

Line 3, Line 4 – Sites allowed to link your images.

 
 
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain2.com [NC]
 

By default all sites are blocked from hotlinking. Only those specified by you are allowed to do so.

Line 5 – File format to block, custom blocking images.

 
 
 
 
RewriteRule \.(jpg|jpeg|png|gif)$ http://hpmouse.googlepages.com/hotlink.gif [NC,R,L]

In between the () are images you intended to block from hotlinking. To add more seperate them with”|”

Change ‘http://hpmouse.googlepages.com/hotlink.gif‘ to a image you’ve set, and whenever image hotlinking is detected, this image will show up. Just make sure where this image is not hotlink protected or your server can go into an endless loop.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail