Knowledge Base
MilesWeb / How-Tos

How to Password Protect Directories with Nginx?

Approx. read time : 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:

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

  • 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:

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

  • 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:

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.

Need help? We’re always here for you.