Set basic Authentication with Nginx

You have a simple website and an admin page. But you may not want to build an authentication system or back-end code to do it. Or, you just want to give the website access to few people only you know — in these cases you can simply use nginx authentication mechanism.

Image source

Nginx auth is a a module comes along with nginx installation, which restricts access to defined pages/areas of the site.

Below are the steps to install and configure auth modules.

sudo apt-get update
sudo apt-get install apache2-utils

Create a user and it’ll prompt you to enter and confirm password

sudo htpasswd -c /etc/nginx/.htpasswd user1

use cat command to view the created username and hashed password

cat /etc/nginx/.htpasswd
user1:$apr1$/woC1jnP$KAh0SsVn5qeSMjTtn0E9Q0

Now, open the conf files and include the authentication requirement locations and the files. An example here below —

location /api {
auth_basic “Administrator’s Area”;
auth_basic_user_file /etc/nginx/.htpasswd;
}