How to password protect directory with Nginx .htpasswd authentication

htt‮ww//:sp‬w.lautturi.com
How to password protect directory with Nginx .htpasswd authentication

To password protect a directory with Nginx using .htpasswd authentication, you will need to do the following:

  1. Create a .htpasswd file containing the username and password for the user who will have access to the password-protected directory. You can use the 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
  1. Add the following block to the Nginx configuration file for the site or location that you want to password protect:
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.

  1. 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.

  2. 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.

Created Time:2017-10-28 21:39:06  Author:lautturi