How to set Password Authentication with Nginx

There are some sensitive pages or sections of the site that you wish to restrict access to, when setting up the webserver.

In this tutorial we’ll learn, how to password protect assets on an Nginx web server running on Centos7.

1. Create the Password File.

We will create a hidden file called .htpasswd in the /etc/nginx configuration directory to store our username and password.

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

Here, “httpauth” is our username.
You will be asked to supply and confirm a password for the user after giving the above command.

Leave out the -c argument for any additional users you wish to add:

sudo htpasswd /etc/nginx/.htpasswd anotherUser

To view the username and the encrypted password for each record:

cat /etc/nginx/.htpasswd
Output
httpauth:$ghgk1$lzxsgyhG$tmCvCfb49vpFEawKGVsuYz.

2. Configure NGINX Password Authentication.

Open your NGINX Vhost file:

sudo vim /etc/nginx/conf.d/example.com

Add the following Directives in the Server Block if you want to enable authentication on the whole site.

auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;

To enable the Authentication on a particular directory:

location /test1.html {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd; }

Test if everything is OK with your config file:

sudo nginx -t 

Restart NGINX service to apply changes:

sudo systemctl restart nginx 

3. To confirm if Password Authentication has enabled or not.

Try to access your restricted content in a web browser. You should be presented with a username and password prompt.

Leave a Reply

Your email address will not be published. Required fields are marked *