1. Install Apache Tools

You need htpasswd command to create .htpasswd with encrypted login details. So install apache tools to get the htpasswd command on your system. Using Apt-Get: Using Yum:

How To SetUp Nginx Virtual Hosts on Ubuntu and Debian

2. Create Credentials File

First you need to create an empty /etc/nginx/.htpasswd file if not exists. You can also do this using -c in htpasswd command. But this overwrites existing file and you may accidentaly overwrite existing file while adding more users. Above command will create new file or just change timestamp for existing file. Let’s start adding new users using htpasswd command.

-m is used for creating md5 encrypted passwords.

3. Edit Nginx Configuration

At this step, edit Nginx configuration file for your server block. Add following entry in the server block you need to authenticate. Update the location path to restrict specific application url of your web application.

4. Reload Nginx Server

To apply the changes to your server configuration reload Nginx server using the following commands. systemctl users can also use the below command.