Contact us
Servers 2 min read · 07/2021

HTTP Basic Auth in Nginx

A guide to easily setting up HTTP Basic Auth for the Nginx web server.

If you need to hide a website behind a simple login and you use the Nginx web server, you can very easily use the HTTP Basic Auth mechanism. If you use the Apache web server, take a look at the article HTTP Basic Auth with Apache and .htaccess

Setting up HTTP Basic Authentication is very simple and quick. Basically, all we need to do is generate a file with the login credentials and add two lines to the domain configuration in nginx.

Creating the credentials file is easy. We can either use an online service, e.g. https://hostingcanada.org/htpasswd-generator/, or use the htpasswd command:

bash
$ htpasswd -bcB .htpasswd username password

This generates a .htpasswd file right in the current directory, and the -bcB parameters used mean:

  • b - The password is entered directly in the command.
  • c - We want to create the file. If the file already exists, it will be overwritten!
  • B - Use bcrypt to encrypt the password

If you don't have the htpasswd command available, you can easily install it from the apache2-utils package (or httpd-tools in the Red Hat world). On Debian/Ubuntu, installation is as simple as:

bash
# On Debian as root
apt install apache2-utils

# On Ubuntu with sudo
sudo apt install apache2-utils

We can then set up the login either just for a certain part of the website using the location directive:

nginx
location /api {
    auth_basic "Login required";
    auth_basic_user_file /path/to/.htpasswd; 
}

Or just as easily for the whole website by placing it directly in the server definition:

nginx
server {
    ...
    auth_basic "Login required";
    auth_basic_user_file /path/to/.htpasswd;

Basic Auth support in Nginx is only basic, so unlike the Apache server, for example, you cannot specify which particular user is allowed to log in. All users defined in the auth file will be able to log in.

For the complete set of configuration options, I recommend going through the official documentation HTTP Basic Auth in Nginx.

Share
LinkedIn Facebook

Need more than an article?

Get in touch with no obligation – a few sentences about what you are dealing with are enough.

Read on

Similar articles

More notes from operations and development.

All advice