Recently, a few of my images started ranking highly on Google Image Search for terms like "icon" or "bullet point". An unfortunate side effect of this new found popularity has been dozens of people hotlinking my images on their websites without permission.

At first, I didn’t really mind, but it reached a point where 9 out of 10 hits on my website were for hotlinked images. So I decided I had to do something about it.

The solution was to write an .htaccess file to block hotlinks, and place it in my photos directory. The code looks something like this:

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

Basically, this code filters out image requests based on the site that sent the request (aka the "referer"). It only affects images with the following extensions: jpeg, jpg, gif, or png.

So, how does it work? The first line turns the rewrite engine on, which allows us to redirect requests. The second line allows viewing images from blank referers; this is important because some browsers won’t send referers, even if the image is linked on your own website. The next three lines allow my own site, and two other sites, to link to my images. The final line redirects anyone else to "bad.jpg" on

Keep in mind, if you’re going to redirect someone to a different image, that image must not be on your server, or you will create an infinite loop!

Alternatively, you can simply block the hotlinked request by changing the last line to the following:

RewriteRule \.(jpeg|jpg|gif|png)$ - [F]

Instead of being redirected, the user will just see a broken image.

You can also use this code to block things besides images (MP3s or Zip files, for example). Just add the file extension into the last line, separated by a pipe character, like so:

RewriteRule \.(jpeg|jpg|gif|png|mp3|zip)$ - [F]

For more fun with .htaccess, check out my article on blocking bots and banning IPs.

Originally Posted by John on 2007-11-02 :

Tagged with:

Filed under: Tips

Like this post? Subscribe to my RSS feed and get loads more!