Knowledge Base Hub

Browse through our helpful how-to guides to get the fastest solutions to your technical issues.

Home  >  How-Tos  >  How to Password Protect Directories with Nginx?
Top Scroll

How to Password Protect Directories with Nginx?

 2 min

You can password protect a directory on the Apache server using .htaccess and .htpasswd files. But, .htaccess files are not supported on Nginx.

Still, you can password protect your directories by using a basic_auth.conf file instead.

Creating the File

1. Log into your server using SSH.

2. Go to your user’s directory.

3. Check for the /home/username/nginx/example.com directory. This isn’t available by default; you need to create it by running the below command:

[server]$ mkdir -p nginx/example.com

4. In this directory, add a file named ‘basic_auth.conf’ with the below command:

location / {
auth_basic "Restricted";
auth_basic_user_file /home/username/nginx/example.com/.htpasswd;
}
  • The auth_basic parameter is simply the title of the prompt seen by the user when he visits this directory.
  • The auth_basic_user_file parameter showcases the location of the password file. Check how its path is set to the /nginx directory.
Note: In this example, the ‘location’ directive password protects the complete domain as it’s pointing to ‘/’.
For password protections a subdirectory, change the ‘location’ directive as below:

location /subdirectory/

5. Execute the following to create the .htpasswd file:

[server]$ htpasswd -c /home/username/nginx/example.com/.htpasswd LOGIN
  • LOGIN indicates the username for authenticating in the login prompt.

6. After you type that command, enter a password and confirm it when you are asked for:

New password:
Re-type new password:
Adding password for user LOGIN

7. You will need to reload the nginx config file.

8. Load the directory your /home/username/nginx/example.com/basic_auth.conf points to in your browser. *In the example above, this would be your domain’s root directory as the ‘location’ directive points to /.

9. Enter a user/password when asked to log in.

  • In this example, LOGIN is your username and you have the password create in the above step.

This way you can password protect your directing with Nginx.

For our Knowledge Base visitors only
Get 10% OFF on Hosting
Special Offer!
30
MINS
59
SECS
Claim the discount before it’s too late. Use the coupon code:
STORYSAVER
Note: Copy the coupon code and apply it on checkout.