Signup/Sign In
PUBLISHED ON: MARCH 2, 2023

Nginx restrict file and directory access.

The default configuration file for Nginx is /etc/nginx/nginx.conf. You can add domains to this configuration but it will become harder to manage. So, it is recommended to add another configuration file (in /etc/nginx/sites-available directory) and add a new domain to it.

How to add a domain to nginx?

1. Start by creating a new configuration file in sites available directory. Name the configuration file with the domain name in it for quick identification.

$ sudo touch /etc/nginx/sites-available/example-domain.com.conf

2. Open the settings file in a text editor.

$ sudo vi /etc/nginx/sites-available/example-domain.com.conf

How to restrict?

1. to restrict access to multiple directories in nginx in one location entry do

...
location ~ /(dir1|dir2|dir3) {
   deny all;
   return 404;
}
...

2. Allow access to specified extensions only.

location ~* ^.+\.(jpg|txt)$ {
            root   /var/www/site;
        }

3. To ensure that the testdir match is chosen instead of the jpg/txt match, use the following locations: (https://nginx.org/en/docs/http/ngx_http_core_module.html#location)

location ^~ /testdir {
  deny all;
  return 404;
}
location ~* ^.+\.(jpg|txt)$ {
  root   /var/www/site;
}

4. If you want to restrict access to folders and subfolders by all IPs except one known IP 155.29.67.30, then add the following Deny and Allow statements as shown.

location /product {
   ...
   Allow 155.29.67.30;
   Deny All;
   ...
}

Finally, You can save the file and exit the editor.

Verify our configuration, then launch Nginx.

It is a recommended practice to test new configurations before loading them to the production server because a single syntax mistake will prevent the Nginx service from running, which will prevent users from accessing your website. You can use the following command to do so.

$ sudo nginx -t -c /etc/nginx/sites-available/domain.com.conf

Enable the site if no issues were discovered. In order to accomplish this, we must build a symbolic link between the site configuration file and the sites-enabled directory using the following command:

$ sudo ln -s /etc/nginx/sites-available/domain.com.conf /etc/nginx/sites-enabled/domain.com.conf

Finally, Start/Restart/Reload the server to load the changes:

$ sudo systemctl restart nginx

or

$ sudo service nginx restart



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.