Preventing hotlinking to your website using .htaccess

on Tuesday, November 25th, 2008 at 3:32 pm

What is hotlinking?

In the web community, “hotlinking” is a curse phrase.
Also known as “bandwidth stealing” by the angry site owner, it refers to linking directly to non-html objects not on one own’s server, such as images, .js files etc. The victim’s server in this case is robbed of bandwidth (and in turn money) as the violator enjoys showing content without having to pay for its deliverance. The most common practice of hot linking pertains to another site’s images.

So how to prevent someone from hotlinking to your website?
How to give them maybe a “nasty” surprise when their hotlinks become so pervasive as to have a significant effect on your bandwidth usage ?

An easy solution is to write this piece of code into your .htaccess file.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.mydomain.com/somelink.ext [R,L]

Of course dont forget to replace
1. “mydomain.com” by your domain name
2. gif|jpg by your desired of file extension you wish to block from referrers (ex: gif|jpg|css|js)
3. http://www.mydomain.com/somelink.ext by the page you wish to redirect to when someone is trying to access (2)

Hope it helps
// Jo

1 Comment »

That works for a while, until you realize that this prevents you from linking someone directly to an image file.
So here’s the approach I use on chady.net – This is the .htaccess contents:

RewriteCond %{HTTP_REFERER} !chady\.net [NC]
RewriteCond %{HTTP_REFERER} !google\. [NC]
RewriteCond %{HTTP_REFERER} !search\?q=cache [NC]
RewriteRule (.*\.(jpg|png|gif)) /showpic.pl?$1

And the showpic.pl file outputs an html snippet that contains an img tag with the source being the requested file.

So what happens is the following:
- if someone hotlinks, they will be served an html chunk that does not affect the bandwidth a lot, and it will display as a broken image for them.
- and if someone links to the image directly, they will get the html (which nicely includes attribution) and they get linked to the image again, this time the browser sets the referer and they can see the image.

Compare:
exhibit 1: http://chady.net/data/art/oldman.jpg
echibit 2: http://chady.net/data/art/ – and click on the oldman.jpg picture again

enjoy :)

Comment by Chady | December 15, 2008 @ 4:56 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment