Enable Hotlink Protection in Nginx

Published in

on

Hotlinking is the biggest issue when we have limited bandwidth to serve, and we all website owners and bloggers should enable hotlink protection to stay away from “resource limit is reached” issues from our web hosting services. Nginx is our favorite platform and probably yours too. Here, in this tutorial, I will explain how to enable hotlink protection in Nginx?

Hotlink Protection

We need to add this location directive in our Nginx configuration file.

location ~ \.(jpe?g|png|gif)$ {
    valid_referers none blocked example.com *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}

Let’s understanding the configuration and meaning of each directive.

  • Use “PIPE” Symbol, “|” to separate file extensions.
  • The directive valid_referers contains the list of site for whom hotlinking is allowed.
  • None – Matches the requests with no Referrer header.
  • Blocked – Matches the requests with blocked Referrer header.
  • *.example.com – Matches all the subdomains of example.com like blog.example.com.

SEO Note: Enabling hotlink protection is a nice idea, but it can hurt SEO rankings badly if not implemented properly. Third party services like search engine image service, social media websites often relies on hotlinking method, so whitelist them all. Just add more domains to valid_referers. Some trusted domains are listed below.

  • *.google.com
  • *.googleusercontent.com
  • *.bing.com
  • *.facebook.com
  • *.twitter.com
  • *.pinterest.com

Another Scenario: If you want to block specific directory where you have tons of extension, and it is hard to write all extension in the configuration file. Then we can simply tell Nginx to block everything under a directory using the following configuration.

location /images/ {
    valid_referers none blocked example.com *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}

Now this will protect every file in that directory.

I hope this will tutorial will help you to enable hotlink in Nginx. In case you have any doubt or issue, raise your voice in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *