How to set up password protection for a specific directory in Nginx?

To set up password protection for a specific directory in Nginx, you can follow these steps:

  1. Generate a password file using the htpasswd command. This file will store the usernames and passwords for authentication. Run the following command, replacing username with your desired username:

    sudo htpasswd -c /etc/nginx/.htpasswd username
  2. Open the Nginx configuration file for the website you want to protect. This file is usually located in the /etc/nginx/sites-available/ or /etc/nginx/conf.d/ directory and has a .conf extension.

  3. Inside the configuration file, locate the server block that corresponds to the website you want to protect.

  4. Add the following lines inside the server block:

    location /path/to/directory { auth_basic "Restricted Access"; # Custom message shown in the login prompt auth_basic_user_file /etc/nginx/.htpasswd; # Path to the password file }

    Replace /path/to/directory with the actual path to the directory you want to protect.

  5. Save the changes and exit the editor.

  6. Test the Nginx configuration for any syntax errors:

    sudo nginx -t
  7. If the test is successful, reload Nginx to apply the changes:

    sudo systemctl reload nginx

Now, when you access the specified directory in your web browser, it will prompt for a username and password before granting access.