Basic HTTP authentication in nginx


Exposing protected and private files on a public web server is generally speaking a bad idea… But… Sometimes the extra work to hide the files behind thick security is just not worth the time. Here’s a quick guide on adding basic HTTP login prompt to a nginx site.

User password prompt

First we will create a user account for prompt to allow. Run this as root/administrator.

sudo -i
cd /etc/nginx
echo -n 'USERNAME:' >> .htpasswd

USERNAME should be the user name you want.

Generate a hashed password. This command will prompt you for the password.

openssl passwd -apr1 >> .htpasswd

The .htpasswd file should look something like this:


Change the ownership of the file to whatever your web server user is running as.

chown www-data:www-data .htpasswd

In this case, the user will be www-data

Edit your nginx site configuration file. Normally these files are located under /etc/nginx/sites-enabled. Find or create a location section that you want to add the prompt for. Add auth_basic and auth_basic_user_file to it. Like this:

location /my_secret/ {
	auth_basic "Secret log in message";
	auth_basic_user_file /etc/nginx/.htpasswd;

The Secter log in message will be visible on the login prompt.

At this point, all you need is to restart the nginx server and you should be set.

systemctl restart nginx