Nginx - Basic authentication

To create a basic authentication layer for a specific page with nginx, you can do the following steps:

1. Add these lines to your nginx config, /etc/nginx/sites-available/myconf:

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

        root /myapp/root/path;
        index index.php index.html index.htm;

        server_name localhost;

        location / {
                try_files $uri $uri/ /index.html;
                auth_basic                     "Restricted";
                auth_basic_user_file   /mnt/DATA/projects/myproject/.htpasswd;

2. Create a .htpasswd file which contains username and password, in the form of username:password ( or username:password:comment). Password must be in encrypted form:

a. Encrypt my desired password (mypassword) for myusername by running the following command line:
trinh@trinh-pc$(PASSWORD="mypassword";SALT="$(openssl rand -base64 3)";SHA1=$(printf "$PASSWORD$SALT" | openssl dgst -binary -sha1 | sed 's#$#'"$SALT"'#' | base64);printf "{SSHA}$SHA1\n")
the result will be: {SSHA}B1y+QGZauvuyKHif5Mi4pqk1HqpvUFZB

b. Create .htpasswd file at (/mnt/DATA/projects/myproject/.htpasswd):


And from now on, when I access the location / (the root) of my website, I will be asked for username and password:

+ For more instructions about nginx basic authentication configuration:
+ For more password-encrypt command: