Shaun Mccran

My digital playground

14
J
U
N
2011

Using url rewriting ( .htaccess or httpd.ini ) to block hot linking resources

After my recent move to HostMediaUK I've been able to see more in depth statistics about one of my sites, including traffic and data usage. This also includes having visibility of other domains that are linking directly to my content. This is popularly known as hot linking, and if you haven't asked permission is considered very impolite.

This also uses up your servers bandwidth rather than theirs. This article explores how I use a URL access file, either .htaccess of http.ini depending on your platform, to stop other domains from linking directly to your hosted resources.

The first caveat of this article is that you must be using a URL rewriting application layer of some kind. This can be Linux or Windows based, it doesn't really matter.

We are going to create a series of Regular expressions to block other domains having access to our files. At the same time we are going to allow certain exceptions such as search engines and emails.

I am using .htaccess re-writing so my example below is based on the syntax for that, but the principle is the same. There are a few checks to run through to ensure each condition is met.

  • The referer is not blank (no value)
  • The referer is not the current site
  • The referer is not an image search bot
  • The referer is not an email client
  • The user agent is not a search engine bot indexer
  • The image in question must be a gif, jpeg, jpg, png, bmp, swf
  • If all those conditions are matched then redirect to a 403 forbidden page

view plain print about
1RewriteCond %{HTTP_REFERER} ^.+$
2RewriteCond %{HTTP_REFERER} ^(?!https?://(?:www\.)?thisDomain\..*) [NC]
3RewriteCond %{HTTP_REFERER} ^(?!https?://(?:images\.|www\.|cc\.)?(cache|mail|live|google|googlebot|yahoo|msn|ask|picsearch|alexa).*) [NC]
4RewriteCond %{HTTP_REFERER} ^(?!https?://.*(webmail|e?mail|live|inbox|outbox|junk|sent).*) [NC]
5RewriteCond %{HTTP_USER_AGENT} ^(?!.*(google|yahoo|msn|ask|picsearch|alexa).*) [NC]
6RewriteRule .*\.(jpe?g|png|gif|bmp|swf) /403.cfm [NC,L]

The two key pieces of information in the example above are the 'thisDomain' value, which is the domain you want to protect. The second is the last line where you list each of the file formats you want to protect and the place you want the denied request to go to. In this example a 403.cfm file. You could put in an image URL here instead if you were more concerned about hot linking images.

TweetBacks
Comments
Back to top