How to configure Nginx to support HTTP Basic Authentication for specific paths?

To configure Nginx to support HTTP Basic Authentication for specific paths, you can follow these steps:

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

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

  1. Create the password file using the 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
  1. Test the Nginx configuration for syntax errors:
sudo nginx -t

If there are no syntax errors, proceed to the next step. Otherwise, review the errors and make the necessary corrections.

  1. Restart Nginx to apply the changes:
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.