How to Enable Basic Authentication on NGINX

Nginx is one of the famous web server used for web hosting. In this tutorial, we will show you how to configure basic authentication on Nginx for your websites.
In this article, we will use htpasswd command line utility from Apache tools package to generate encrypted credentials file.

1. Install Apache Tools

First of all we need htpasswd command to create .htpasswd with encrypted login details. So let’s install apache tools to get the htpasswd command on your system.

Using Apt-Get:

sudo apt-get install apache2-utils

Using Yum:

yum install httpd-tools

2. Create Credentials File

Now we need to create an empty /etc/nginx/.htpasswd file if not exists.

touch /etc/nginx/.htpasswd

Above command will create new file or just change timestamp for existing file. Let’s start adding new users using below commands.

htpasswd -m /etc/nginx/.htpasswd user1
htpasswd -m /etc/nginx/.htpasswd user2

Note: -m is used for creating md5 encrypted passwords.

3. Edit Nginx Configuration

Now edit Nginx configuration file for your server block. Add following entry in the server block you need to authenticate.

server {
listen 80 default_server;
server_name _;
root /usr/share/nginx/html;
location / {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}

Update the location path to restrict specific application url of your web application.

location /restricted/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}

4. Reload Nginx Server

To implement these changes to your server configuration reload Nginx server using the following commands.

sudo /etc/init.d/nginx reload

systemctl users can also use the below command.

sudo systemctl reload nginx.service