Password protect a directory with index listing in nginx

Install htpasswd utility:

apt install apache2-utils # For Debian/Ubuntu
dnf install httpd-tools # For Fedora/RHEL
Create the .htpasswd file: This file will store usernames and the hashed passwords:
htpasswd -c /etc/nginx/.htpasswd your_username
To add more users later without overwriting the file, omit the -c flag.

Edit your nginx configuration file:
location /protected/ {
  auth_basic "Restricted Area";
  auth_basic_user_file /etc/nginx/.htpasswd;
  autoindex on; # To enable directory listing (indexes)
}
Test and reload nginx:
nginx -t
sytemctl reload nginx