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):


myusername:{SSHA}B1y+QGZauvuyKHif5Mi4pqk1HqpvUFZB


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




References:
+ For more instructions about nginx basic authentication configuration: http://wiki.nginx.org/HttpAuthBasicModule
+ For more password-encrypt command: http://roger.steneteg.org/441/basic-authentication-with-nginx/

Comments