To set up password protection for a specific directory in Nginx, you can follow these steps:
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
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.
Inside the configuration file, locate the server
block that corresponds to the website you want to protect.
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.
Save the changes and exit the editor.
Test the Nginx configuration for any syntax errors:
sudo nginx -t
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.