/nginx, image, hotlink

Prevent image hotlinking / stealing from your site with nginx

Have you noticed other sites hotlinking to your images or other assets? Are they eating up your bandtwitch? Or you just want to proactively prevent that? If so, there's a very easy way to do so with a simple configuration on nginx.
Open up nginx config file for your site and add another location block like this:

server {
    # your normal site configuration is here

    location ~* \.(gif|png|jpe?g)$ {
        valid_referers none blocked server_names ~\.google\. ~\.bing\. ~\.yahoo\. ~\.facebook\. ~\.yoursite.com;
        if ($invalid_referer) {
            return 403;
        }
    }
}

With above, we're sending 403 Forbidden error status code whenver an image is requested from a referer that is not in our approved list.
valid_referers lists sites which we want to allow hotlinking our images. Remember to change ~\.yoursite.com to your actual site domain.
If you want to block other file types, just add an extra pipe "|" and file extension, like this (gif|png|jpe?g|bmp|tiff|pdf)

Going one step further, you can serve one specific image every time a not approved sites tries to hotlink to your assets. To do that add below config:

server {
    # your normal site configuration is here

    location ~* \.(gif|png|jpe?g)$ {
        valid_referers none blocked server_names ~\.google\. ~\.bing\. ~\.yahoo\. ~\.facebook\. ~\.yoursite.com;
        if ($invalid_referer) {
            rewrite (.*) /path/to/image/hotlinking-denied.jpg redirect;
        }
    }
    # prevent redirect loop
    location = /path/to/image/hotlinking-denied.jpg { }
}