Prevent Image Hotlinking in ASP.NET/Core Applications

Introduction

As a website developer, we sometimes don't want the images on our own website to be directly referenced and showed on other's website. It can cause a lot network bandwidth for our datacenters in some cases, which means costing money for us to pay for the one who use our images.

For example, your website is A.com, you have an image on http://a.com/facepalm.jpg and B.com used your image on b.com by putting an <img> tag in their html, it can cause network request going in to your server consuming your resources.

A lot of websites prevent image hotlinking. Let me show you how we can do it in ASP.NET or ASP.NET Core application.

The technique I use is URL Rewrite. As we know, every http request has some headers, one of them is the "HTTP referer". You can check more details on Wikipedia here. It applies to image files also, if the image is hotlinking from another website. It will have HTTP referer values of another website.

In the example above, if the user lands on b.com visiting http://a.com/facepalm.jpg, for a.com's web server, the http requst for this particular image will have an http header named "referer" with value of "http://b.com....". This is where we will check and block the request.

This rule means, for the image file type that ends with .gif, .jpg, .png, check the HTTP Referer header, if it is not starting with "http://a.com" return the image "/content/images/no_hotlinking.png", which is a prepared warning image like below:

Then, add this section into your web.config, under system.webServer node

Many thanks. We where test crawling our website and noticed a difference in the URLs. Now we know why :) It's already hard to keep consistency when developing applications in a team. Now even need to be more careful with selecting which UrlEncode to use by default.