Setup password authentication in nginx

From DevOps Notebook
Revision as of 09:45, 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;
</<syntaxhighlight>

Example:
<syntaxhighlight lang="nginx">
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;
    }
}