Tim Igoe's Web Design, Development and Hosting Blog

Blog > .htaccess to disable hotlinking

If people start hotlinking images that you host, it ends up costing you bandwidth for no gain for you, however, its really easy to defeat this for most users using a htaccess file in your sites root.

You could place it in the images folder only, this would limit hotlinking to images only then. There are 2 ways of disabling images, the less nice way which gives a 403 error (access forbidden) - this way the users will see a red 'x' or the image will be hidden by the browser. Or the nicer way, showing an alternative image instead that discourages hotlinking.

.htaccess


RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://site.com/.*$ [NC]
RewriteRule .*.(gif
|jpg|png|ico)$ - [F,NC,L]


This will disable hotlinking for gif, jpg, png and ico type files and show a red 'x'. For this to work, you will need to replace site.com with your domain name.

.htaccess



RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http://site.com/.*$ [NC]

RewriteRule .*.(gif|jpg|png|ico)$ http://site.com/nolinking.jpg [R,NC,L]


The difference with this version, is that it will show the user an alternative image rather than the one they asked.

It is a very easy way to save yourself bandwidth if you get someone stealing one (or more) of your images.

Similar Articles from the web

.htaccess to disable hotlinking

In reply to this Elizabeth said hotlinking

Hi, I have tried using this code and to no avail. I had previously tried a different bit and it did not work either. The hotlinking is disallowed but the image to show up that states no hotlinking will not appear. I have replaced the url for both the rewrite cond and the rewrite rule, any suggestions? Thank you for your time.

In reply to this TimIgoe said Image Block

To stop the blocking of the image if it is hosted on the same domain, you need one further line adding into the re-write.

Before the re-write rule itself, add a line like

.htaccess


RewriteCond %{REQUEST_FILENAME} !nohotlink.jpg [NC]


This basically makes sure we're not working on the file that is the 'no hotlinking' image, if it is, we stop processing, if its not, we then carry on and show the user the no hotlinking image.

Hope that helps.

Post a reply