How to Password Protect Web Directories on Nginx

In this guide, you’ll learn how to password protect a directory on your website by implementing a username/password authentication using nginx HTTP basic auth.
HTTP basic authentication allows you to stop other people who don’t have the login credentials from accessing the section/folder you are protecting.
Install Apache Utils
To start out, you need apache2-utils, this package contains the htpasswd package which allows you to create the username and the password. To install the package use the following command.
sudo apt install apache2-utilsCreating the Password File
In this step, you need to create a file that will hold your username and password combinations. You can do this by using the following command.
sudo htpasswd -c /etc/nginx/private JackReplace Jack with your username and private with the folder or section that you’re protecting.

Once you type the above command, you will be prompted to set a password for the username you selected, type the password twice.
To verify the file, you can check it with the cat command.

You can see in the screenshot above, the file contains the username and the encrypted password.
Setup Basic HTTP Auth
Open nginx config file with nano text editor.
nano /etc/nginx/sites-available/default
And add the following line under location.

location /wp-admin — will password protect the section /wp-admin, so when you browse to mysite.com/wp-admin you will be prompted to enter username and password.
auth_basic_user_file — Is the path where the htpasswd file is located.
Once you have added your own configuration press CTRL + X to save the file and reload nginx using the command.
sudo systemctl reload nginxNow I will switch to the web browser and type ‘webtest.com/wp-admin’.

I have been prompted to a login form where I need to enter the correct credentials if I want to access the content.
Conclusion
Sometimes a website is good to be under a password protection, or to have an extra layer of security by blocking access to a specified folder. Most web servers have a password directive built in, including Nginx.
Thank you!





