&sect:2022-12-22

Nginx Let’s implement Basic Authentication in Nginx by following.

We will take help from Apache Utils to generate the credentials. If the server doesn’t have Apache HTTP installed, then you need to install the utils separately as below. If unsure, you can execute htpasswd to see if it works. If it doesn’t, then you know you need to install it.

CentOS/RHEL 8

dnf install httpd-tools CentOS/RHEL 7

yum install httpd-tools Ubuntu

apt-get install apache2-utils


&archLinux


Let’s create the credentials similar to how we did in Apache.

Don’t forget to replace chandan with the real user name you want Next, we need to configure Nginx, so it restricts the particular URI with the password.

Let’s assume we need to protect /admin URI Add the following in nginx.conf or other active Nginx configuration file

location / {
        auth_basic "Default Root Area";
        auth_basic_user_file /etc/nginx/.htpasswd;
        root   /usr/share/nginx/html;
        index  index.html index.htm;
     }

then Restart Nginx

What if you have to restrict the entire website getting served through Nginx?

Easy!

Add the following in nginx.conf or active configuration file under location / { directive

auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;