How to setup basic http authentication with nginx

The following commands were tested on Ubuntu 18.04

Install apache2-utils

You’ll need the htpassword command to configure the password that will restrict access to the target website. This command is part of the apache2-utils package, so the first step is to install that package.

sudo apt-get install apache2-utils

Setup HTTP Basic Authentication Credentials

sudo httpasswd -c /etc/nginx/.htpasswd username_here

It will prompt for password input

Update nginx vhost configuration

Open your vhost configuration file in nginx and add the auth_basic lines

. . .
location / {
	. . .
    auth_basic "Private Property";
    auth_basic_user_file /etc/nginx/.htpasswd;
    . . .
}
. . .

Once this is done, restart nginx server and open the domain in browser.

sudo /etc/init.d/nginx restart

When you open the website in browser, you should be prompted for username and password