Setup password authentication in nginx

From DevOps Notebook
Revision as of 09:43, 9 April 2020 by MilosZ (talk | contribs)

Generate htpasswd password and put it in file

# echo "admin:$(openssl passwd -apr1 Q89C82CNCeLxfSX3)" | sudo tee -a /etc/nginx/.htpasswd
# cat /etc/nginx/.htpasswd

In server block, under location you wanna add password for, add:

auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;

Example:

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;
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}