To password protect a directory with Nginx using .htpasswd authentication, you will need to do the following:
htpasswd
utility to create the .htpasswd file. For example, to create a .htpasswd file called .htpasswd
in the current directory, with a username of user
and a password of password
, you can use the following command:htpasswd -c .htpasswd user
You will be prompted to enter the password for the user. You can add multiple users to the .htpasswd file by running the htpasswd
command without the -c
option:
htpasswd .htpasswd user2
location /protected/ { auth_basic "Restricted Area"; auth_basic_user_file /path/to/.htpasswd; }
This block specifies the location of the directory that you want to password protect (/protected/
in this example), and the location of the .htpasswd file (/path/to/.htpasswd
in this example). The auth_basic
directive specifies the message that will be displayed to users when they are prompted for a username and password, and the auth_basic_user_file
directive specifies the location of the .htpasswd file.
Save the Nginx configuration file and reload Nginx to apply the changes. You can use the nginx -s reload
command to reload the Nginx configuration.
Test that the password protection is working by accessing the protected directory in a web browser. You should be prompted for a username and password when you try to access the protected directory.
Note that the .htpasswd file should be stored outside of the document root of your web server to prevent it from being accessed directly through the web.
For more information on password protecting directories with Nginx, you can refer to the Nginx documentation.