Preview:
# =============== first let''s create user/password:
# 1: user

$> sudo sh -c "echo -n 'sammy:' >> /etc/nginx/.htpasswd"

# 2: passsord

$> sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"

# You can repeat this process for additional usernames. You can see how the usernames and encrypted passwords are stored within the file by typing:

# let's see what we did:

$> cat /etc/nginx/.htpasswd

# Output (something like)
# sammy:$apr1$wI1/T0nB$jEKuTJHkTOOWkopnXqC1d1

# then, we need to add configuration:
# at /etc/nginx/sites-available/default (or whatever your configuration is):

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 /myrestrictedfolder {                  #<--- new here
        rewrite ^(.*[^/])$ $1/ permanent;           #<--- new here
        auth_basic "Restricted Content";            #<--- new here
        auth_basic_user_file /etc/nginx/.htpasswd;  #<--- new here
    }                                               #<--- new here

    location / {
        try_files $uri $uri/ =404;
    }
}

# then restart nginx daemon:

$> sudo service nginx restart


#you will be asked for basic user/password when entering: http://localhost/myrestrictedfolder/
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter