k4zek4ge
10/21/2019 - 9:06 AM

Nginx password protect a directory

# install a password file creation tool
sudo apt-get install apache2-utils

sudo htpasswd -c /etc/nginx/.htpasswd a_user
#After typing that command, enter a password and confirm it when prompted:
New password: 
Re-type new password: 
Adding password for user a_user

# to view content of pwd file
cat /etc/nginx/.htpasswd

# edit nginx site config file
sudo nano /etc/nginx/sites-enabled/learning.toto.fr

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.html index.htm;

    server_name localhost;

    location / {
        try_files $uri $uri/ =404;
    }
    
    location /path_to_dir_to_protect {
        try_files $uri $uri/ =404;
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

# restart nginx
sudo service nginx restart