Nginx Basic Auth without htpasswd-tools
Mon 10 November 2014 by Thejaswi PuthrayaSometimes you may want to hide your staging server or project under development from search engines and prying eyes but you don't want to take a lot of pain. HTTP Basic Auth is one solution (can be used as a proper authentication mechanism for web-apps as well) to allow only authorized people from visiting the site under wraps. On visiting the site, the user will be prompted for a username and password before displaying the site.
It's fairly easy to setup HTTP basic auth on nginx. You need to specify which location will use the authentication and what the authentication details are.
First, on the nginx config:
location / { auth_basic "Restricted Access"; auth_basic_user_file /path/to/basic_auth_file/.htpasswd; ... }
The .htpasswd file (can have any name but apache seems to have started this trend so let's play on for now) that you create will have the username separated by a colon (:) followed by the encrypted password hash per line. For example:
username1:<encrypted_password_hash1> username2:<encrypted_password_hash2> ...
To create the encrypted password hash, the htpasswd-tools package is recommended but it is possible to create the encrypted hashes without the package. All you need is the openssl package (which comes bundled by default on most linux distributions):
$ openssl passwd -crypt Password: Verifying - Password: ZET0ZiC0DqcF2
On running the above command, it prompts you for the password and to confirm it and then will output a hash. Copy the hash and enter it in your htpasswd file and you are good to go after restarting nginx.