How to password protect NGINX web directories wihout htpasswd?


  1. nginx
  2. openssl
  3. vim

Step 1: Make .htpasswd file

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

You can type any name in place of username.

Step 2: Add password to .htpasswd file

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

This command will ask you what password you want and encrypt it.

Step 3: See how passwords are stored

cat /etc/nginx/.htpasswd

You can add additional usernames and passwords by repeating the same process.

Step 4: Configure Password Authentication

Edit your desired server block. In this case, we are adding password authentication on default block

sudo vim /etc/nginx/sites-enabled/default

Add this line inside location / { } block.

If you don't add this line under location / {} it may loop the user authentication.

auth_basic "Login";
auth_basic_user_file /etc/nginx/.htpasswd;

Step 5: Save and Close the file

Step 6: Restart the NGINX process

sudo nginx -s reload