Securing Nginx sites with Basic Auth

Nginx Jan 27, 2025

Creating user

  1. Install apache2-utils for (Debian, Ubuntu) or httpd-tools for (RHEL/CentOS/Oracle Linux). Verify htpasswd command exists.
  2. Create a new user with htpasswd command.
sudo htpasswd -c /etc/nginx/.htpasswd sam
# -c creates new file
  1. Verify if the new user has been created.
 cat /etc/nginx/.htpasswd
  1. To add other users, run the following, replace smith with your desired username.
sudo htpasswd /etc/nginx/.htpasswd smith

Adding Basic Auth for a site

  1. Go to your desired site in sites-available.
  2. To add the auth for a specific block, add the following inside the location block.
location /status {
        auth_basic "Administrator’s Area";
        auth_basic_user_file /etc/nginx/.htpasswd;
        stub_status ;
    }
  1. To add the auth for the whole site, you can add it directly in the server block. And you can turn off the auth for specific location as below.
server {
    ...
    auth_basic           "Administrator’s Area";
    auth_basic_user_file conf/htpasswd;

    location /public/ {
        auth_basic off;
    }
}

Reference:
Original Nginx Guide: https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/

Tags