nginx prevent image access

How to Prevent Direct Access to Images in NGINX

Sometimes you may need to block direct access to images on your website. That is, you may want to allow images to be loaded only within your web pages via img tag, but may want to disallow people from directly requesting image URL on their browsers. This is because, many times, people download images from other websites and use it on their own site. Sometimes they even hotlink images, without even downloading them. To avoid these situations, it is advisable to block direct access to images on your website. In this article, we will learn how to prevent direct access to images in NGINX.


How to Prevent Direct Access to Images in NGINX

Here are the steps to prevent direct access to images in NGINX.


1. Open NGINX Configuration File

Open NGINX configuration file in text editor.

$ vi /etc/nginx/sites-available/default

You have setup virtual hosts on your NGINX server, then open its configuration file in a text editor.


2. Prevent Direct Access

Add the following lines inside server block to disable direct access to jpg, png and gif files.

location ~* \.(jpg|png|gif)$ {
   valid_referers example.com www.example.com;
   if ($invalid_referer) {
      return 403;
   }
}

The above location block will process requests for jpg, png and gif files. It will check if the referer is your domain, example.com or www.example.com. That is, it will check if the request came from your website or not. If not, then NGINX will return 403 Access Forbidden response message.

Replace example.com with your domain name. Replace jpg, png, gif with the file extensions for which you want to block direct access.

So your server configuration will look like.

server {

  location {
  ...
  }

  location ~* \.(jpg|png|gif)$ {
   valid_referers example.com www.example.com;
   if ($invalid_referer) {
      return 403;
   }
  }

...

}


3. Restart NGINX Server

Restart NGINX server to apply changes.

$ sudo service nginx restart

In this article, we have learnt how to block direct access to image files in NGINX.

Also read:

How to Prevent Direct Access to Images in Apache
How to Know Which Shell I am Using in Linux
How to Find Package Details in RHEL, CentOS, Fedora
How to Delete Objects in Django
How to Delete File or Folder in Python

Leave a Reply

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