How to Enable Hotlink Protection in Nginx?

Hotlinking is the biggest issue when we have limited bandwidth to serve and we all webmasters should enable hotlink protection to stay aways from resource limit is reached issues. Nginx is our favorite platform and here 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;
    }
}

Lets understanding the configuration.

  • 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.

SEO Note: Enabling hotlink protection is a nice idea but it can hurt SEO rankings badly if not used properly. Third party services like Search Engine Images, Social Networking Websites 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.

Share This

Author: AtulHost

Hi, I'm Atul Kumar Pandey, a full time blogger by passion and profession. Since I started working on the web industries many years ago, with my all expertise I blog on atulhost.com, where my main objective is to build and market quality contents and reviews.