Nginx. Directory Access Restriction

In this article I will give examples of restricting access to files or directories by IP address or username and password.

You can completely deny access to a specific directory like this:

location ^~ /folder1/ {
        deny all;
    }

Several directories can be specified like this:

location ~* ^/(folder1|folder2)($|\/) {
        deny all;
    }

Or so:

location ^~ /folder1/ {
        deny all;
    }

location ^~ /folder2/ {
        deny all;
    }

I’ll give an example of how to allow access to specific IP addresses or networks:

location ^~ /folder1/ {
        allow 192.168.0.0/24;
        allow 192.168.5.5;
        allow 192.168.5.8/32;
        deny all;
    }

Restrict access by login and password as follows:

location ^~ /folder1/ {
        auth_basic "Hello, please login";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

Generate the password with the command below (or for example here https://hostingcanada.org/htpasswd-generator):

openssl passwd

Let’s say the username is “admin”, and the password is “ixnfo”, after entering the command above, in encrypted form the password looks like this – q7h194Y1SBgxo, now add it to the .htpasswd file:

admin:q7h194Y1SBgxo

To apply configuration changes, for example, if the operating system is Ubuntu, you must run the command:

service nginx reload

Or just restart nginx:

service nginx restart

Before applying the configuration, it is advisable to check it (since in case of errors nginx will not start):

nginx -t

It is possible to restrict access simultaneously by IP addresses and by login/password:

location ^~ /folder1/ {
        allow 192.168.0.100;
        deny all;
        auth_basic "Hello, please login";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

An example of a login/password restriction for a directory with php files:

  location ^~ /folder1 {

   location ~ \.php$ {
                try_files $uri =404;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

     auth_basic "Hello, please login";
     auth_basic_user_file /var/www/.htpasswd;
   }

To restrict access, for example, only to php files in the directory “folder1”:

location ~* ^/folder1/.+\.php {
        allow 192.168.0.100;
        deny all;
    }

See also my article:
How to configure IP access in nginx

Leave a comment

Leave a Reply