This brief tutorial shows students and new users how to use Apache2 utils to generate basic password authentication for Nginx directories. This feature can be used to protect directories with basic passwords. It’s a great feature and can be used to add a layer of protection to existing directories. To protect Nginx directories with basic password authentication, the steps below are a great place to start:

Install Apache2 HTTP Utility

Again, Nginx doesn’t have this tool. so if you need to protect Nginx directories, install this Apache2 tool. To install, run the commands below

Create a .htpasswd file

Now that you’ve installed Apache2 utils, run the commands below to create a password file for users. The commands below will prompt you to create a new password for the username specified and store the file in the directory defined. /etc/nginx/.htpasswd Replace myusername with the username you wish to use. You can choose any directory to save the htpasswd file. however, you must specify the location when configuring Nginx. After running the commands above, a new hidden passwd file for the username you selected will be saved in the /etc/nginx/.htpasswd file. Below is the output of the command:

Protect Nginx Directories

Now that the password file is created, use the highlighted code block below to protect a Nginx directory. Nginx default site configuration file is at /etc/nginx/sites-available/default Add these lines below to the directory you want to protect. Save the file. Every time you attempt to browse to the /Private directory, you should get a basic HTTP authentication prompt to type a username and password. To protect the entire Nginx site, define the root location to protect:  /var/www/html Example: Save the file. The next time you browse the domain, you will be prompted as shown below. That’s it! You may also like the post below: