prevent image hotlinking in nginx

How to Prevent Image Hotlinking in NGINX

Image hotlinking is when another website links to images on your website images without hosting those images on their own server. It slows down your website and increases your data bandwidth. So it is important to disable image hotlinking on your website. Here’s how to prevent image hotlinking in NGINX.

How to Prevent Image Hotlinking in NGINX

Here are the steps to prevent image hotlinking in NGINX.

1. Open NGINX Configuration File

Open terminal and run the following command to open NGINX server configuration file.

$ sudo vi /etc/nginx/nginx.conf

If you have configured separate virtual hosts for your website (e.g www.website.com), such as /etc/nginx/sites-enabled/website.conf then open its configuration with the following command

$ sudo vi /etc/nginx/sites-enabled/website.conf

Bonus Read : How to Harden NGINX Server

2. Disable Image Hotlinking in NGINX

Add the following location block inside server block to prevent image hotlinking in NGINX from all domains except your domain (e.g website.com)

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

Let us look at the above code line by line. The first line will match various image file extensions. If you want to add any other extension, you can add a new pipe “|” along with the new extension.

In the next line, valid_referers lists all the domains that are allowed to link to your website images. Mention your website (e.g website.com) in it. You can also add any other domains that you want to give access to. You can also include IP addresses here.

If the request is from a domain/IP that is not mentioned in valid_referers NGINX will include it in invalid_referer and return “403: Access Forbidden” response.

Bonus Read : How to Setup NGINX Virtual Hosts on CentOS

If you want to prevent hotlinking for files in a specific directory such as /uploads/ then add the following lines in your NGINX configuration file.

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

Bonus Read : How to Enable CORS in NGINX

3. Restart NGINX Server

Finally, run the following command to check syntax of your updated config file.

$ sudo nginx -t

If there are no errors, run the following command to restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

That’s it! Hopefully the above tutorial will help you prevent image hotlinking in NGINX.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it today!

mm

About Ubiq

Ubiq is a powerful dashboard & reporting platform for small & medium businesses. Build dashboards, charts & reports for your business in minutes. Get insights from data quickly. Try it for free today!