Derek Lawless

There is always sunshine / Far above the grey sky

Let’s begin by stating that Basic Authentication is likely not the authentication method you’re looking for. It has a number of shortcomings, not least of which is it transmits the password.

Granted, it base64 encodes the username and password first but this is reversible encoding.

Caveats aside, it does still have its uses - perhaps you want to restrict casual access to files or web applications available on your internal network only without the complexities of OAuth, Active Directory integration, or similar.

To secure endpoints in NGINX using Basic Authentication, follow these steps:

  1. On the NGINX host, type the following in your terminal:
# Substitute {USERNAME} for the one you want to use e.g. 'admin'
printf "{USERNAME}:`openssl passwd -apr1`\n" >> .htpasswd

Enter an appropriate strength password when prompted. For simplicity, consider creating this file in an appropriate location e.g. /etc/nginx/sites-available.

  1. Update the NGINX configuration(s) for each endpoint you wish to secure:
location / {
	# Display a title on the Basic Authentication browser challenge dialog (if supported)
	auth_basic "Administration Area"
	# The absolute path to the .htpasswd file
	auth_basic_user_file /etc/nginx/sites-available/.htpasswd;
  1. Ensure the .htpasswd file is readable by NGINX workers:
chmod 644 .htpasswd
  1. Verify the NGINX configuration and reload/restart:
sudo nginx -t -c /etc/nginx/nginx.conf
sudo service nginx reload
© 2022 Derek Lawless. Built with Gatsby