How to add HTTP Basic auth in nginx?

How to assign http basic auth for a directory and all files in it with nginx.

The contents of /etc/nginx/sites-available/default:
server {
 listen 80 default_server;
 listen [::]:80 default_server;

 root /var/www/html;

 # Add index.php to the list if you are using PHP
 index index.php index.html index.htm index.nginx-debian.html;

 server_name 111.111.111.11;

 location / {
 try_files $uri $uri/ /index.php?$query_string;
}

 location /admin {
 auth_basic "Admin Login";
 auth_basic_user_file /etc/apache2/.htpasswd;
}

 location ~ \.php$ {
 include snippets/fastcgi-php.conf;

 location unix:/run/php/php7.3-fpm.sock;
}

 location ~ /\.ht {
 deny all;
}
}


We need to put authorization on the directory /var/www/html/admin
The problem is that the authorization does not work if you access files in this directory, for example site.ru/admin/index.php

How to fix it?
March 19th 20 at 08:45
1 answer
March 19th 20 at 08:47
Solution
server {
 listen 80 default_server;
 listen [::]:80 default_server;
 root /var/www/html;
 index index.php index.html index.htm index.nginx-debian.html;
 server_name 111.111.111.11;
 location / {
 try_files $uri $uri/ /index.php?$query_string;
}
 location ^~ /admin/ {
 auth_basic "Admin Login";
 auth_basic_user_file /etc/apache2/.htpasswd;
 location ~ \.php$ {
 include snippets/fastcgi-php.conf;
 location unix:/run/php/php7.3-fpm.sock;
}
}
 location ~ /\.ht {
 deny all;
}
}

Find more questions by tags System administrationNginx