To password protect a directory with Nginx using .htpasswd authentication, you can follow these steps:
- Create a .htpasswd file that contains a list of username and password pairs. You can create this file using the “htpasswd” command. For example:
htpasswd -c /etc/nginx/.htpasswd user1
- Add the following code to your Nginx server block configuration file:
location /protected/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
This will protect the “/protected/” directory and prompt for a username and password when accessed. The “auth_basic” directive sets the authentication realm, and the “auth_basic_user_file” directive specifies the location of the .htpasswd file.
- Reload or restart Nginx for the changes to take effect.
- To add more users to your .htpasswd file you can use the following command :
htpasswd /etc/nginx/.htpasswd user2
Note: Keep in mind that the authentication file is stored in plain text format and can be easily read if someone has access to it. As an alternative, you can use a more secure authentication method, such as SSL/TLS certificates or OAuth2.