Nginx - Implement HTTP Basic Auth
Introduction
When one needs to lock down a site for private access, implementing HTTP basic auth is often the quickest and easiest solution as it requires minimal webserver configuration, rather than happing to implement some application layer logic. This is especially true when one needs to lock down an application that one didn't develop themselves, and does not have any native authentication solution. In such scenarios, one can just implement the HTTP basic authentication on the reverse proxy in front of the application.
Steps
Creating The Htpasswd File
Install the apache2-utils in order to be able to make use of the htpasswd command for creating our htpasswd file
sudo apt update && \
sudo apt install apache2-utils -y
Create an auth directory to hold the htpasswd for our sites
sudo mkdir /etc/nginx/auth
Now create the the htpasswd file for our user (in this case user1)
sudo htpasswd -c /etc/nginx/auth/$SITE_NAME user1
-c
flag is to tell htpasswd to create the file. If the file already exists, then remove this to add users to the file.
Edit Nginx Site Configuration
Now we need to configure our site's configuration file in order to tell Nginx to enable HTTP basic authentication, and specify the path to our htpasswd file.
You can either do this in a location directory to lock down that location. E.g.
location /api {
auth_basic "Administrator’s Area";
auth_basic_user_file /etc/nginx/auth/my-site;
}
... or if you want it to apply to the entire site, you can put it at the server
level
server {
...
auth_basic "Administrator’s Area";
auth_basic_user_file /etc/nginx/auth/my-site;
location /api {
...
}
}
If you want to apply it to the entire site, but disable it for specific locations, then use auth_basic off;
within those locations
server {
...
auth_basic "Administrator’s Area";
auth_basic_user_file /etc/nginx/auth/my-site;
location /public/ {
auth_basic off;
}
}
References
First published: 29th October 2021