To configure Nginx to support HTTP Basic Authentication for specific paths, you can follow these steps:
Open your Nginx configuration file using a text editor. The location of the configuration file may vary depending on your system, but common locations include /etc/nginx/nginx.conf
or /etc/nginx/conf.d/default.conf
.
Inside the server
block, add the following location block to specify the path you want to protect:
location /path/to/protect {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}
Replace /path/to/protect
with the actual path you want to protect. For example, if you want to protect the /admin
path, replace /path/to/protect
with /admin
.
htpasswd
utility. Run the following command to create the file and add a username and password:sudo htpasswd -c /etc/nginx/.htpasswd username
Replace username
with the desired username. You will be prompted to enter and confirm the password.
If you already have an existing password file and want to add new users, omit the -c
flag:
sudo htpasswd /etc/nginx/.htpasswd username
sudo nginx -t
If there are no syntax errors, proceed to the next step. Otherwise, review the errors and make the necessary corrections.
sudo systemctl restart nginx
Now, when accessing the specified path, Nginx will prompt for a username and password based on the credentials stored in the password file.