Tip #34: Did you know... How to stop hot-linking from your site using URL Rewrite in IIS 7.0?

Hot-linking is a direct linking to a web-site's file (images, videos etc). An example can be using an <img> tag to display a JPEG image someone finds at your web site. This is also referred to as bandwidth theft as when someone is viewing this site, they will be using the bandwidth of your site to display the JPEG image. The other words used to describe this are leeching, piggybacking, direct linking or offsite image grabs to name a few.

Let's say you have the below copyright image at your web site https://www.contoso.com/img1.jpg which you would like to prevent from hot linking.

welcome

URL Rewrite module in IIS 7.0 can be used to achieve this in a very simple way. I will tell you how to do this from IIS Manager. Open IIS Manager and select "Your Web Site (Contoso.com in this case)". In the feature view click "URL Rewrite and click "Add Rules..." in the "Actions" pane. Select "Blank Rule" to start with. This will open up the "Edit Rule" property page. Fill the property page as shown below:

Url_Rewrite

Let me now explain what we have done on this property page:

  • Specified name of the rule as "Prevent Leeching". This must be a unique rule.
  • Every requested URL will be matched as the pattern is ".*" and is a regular expression.
  • Added two condition and specified both the condition to be satisfied (see "Logical Grouping" is "Match All")
    • HTTP_REFERRER does not match empty as it can be a direct reference to the image
    • HTTP_REFERRER does not match my own site https://www.contoso.com
  • If the above two conditions are satisfied (apparently meaning the request is coming from any other site), we are just redirecting it to pick up some other image which can be anything

And that's it. So without writing even a single line of code we are able to prevent hot-linking.

One important thing to remember is that URL Rewrite should be installed for this to work. You can install X86 version here and X64 here. This module is supported for IIS 7.0 and you should be running IIS 7.0 to take advantage of it. Also if you are working with VWD (Visual Studio for Web Developers) your project should be configured to work with IIS 7.0 and not any other web server.

This was one of the cool features showcased in PDC 2008 for IIS 7.0. For other cool features including this please see this complete video at channel9.

Don Raman 
SDET, IIS Team