Nginx Basic Authentication Setup

Install Apache Utilities

Install the apache2-utils package which provides htpasswd utility for creating and managing basic authentication password files:

sudo apt install apache2-utils

Create Password File

Generate and manage password files for authentication. The -c flag creates a new file and should only be used for the first user:

# Create new password file
sudo htpasswd -c /etc/nginx/.htpasswd username

# Add additional users
sudo htpasswd /etc/nginx/.htpasswd another_user

Protect Entire Domain

Configure authentication for the entire website domain. All paths will require authentication:

server {
    listen 80;
    server_name example.com;

    auth_basic "Restricted Access";           # Message shown in login prompt
    auth_basic_user_file /etc/nginx/.htpasswd;  # Path to password file

    root /var/www/html;
    index index.html;
}

Protect Specific Location

Apply authentication to specific paths or directories while keeping others public:

server {
    listen 80;
    server_name example.com;

    location /admin {
        auth_basic "Admin Area";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

    location /api {
        auth_basic "API Access";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

Protect with IP Whitelist

Combine IP-based access control with password authentication for enhanced security:

server {
    listen 80;
    server_name example.com;

    location /admin {
        satisfy any;        # Match any condition (IP or auth)

        allow 192.168.1.0/24;  # Allow internal network
        allow 10.0.0.0/8;      # Allow VPN
        deny all;              # Deny everyone else

        auth_basic "Admin Area";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

Validate & Reload

After making configuration changes, always test and reload Nginx:

# Test configuration
sudo nginx -t

# Reload Nginx
sudo systemctl reload nginx

Manage Users

Commands for managing user access credentials:

# Change password
sudo htpasswd /etc/nginx/.htpasswd username

# Delete user
sudo htpasswd -D /etc/nginx/.htpasswd username

# List users
cat /etc/nginx/.htpasswd

Security Best Practices

  1. Store .htpasswd outside web root
  2. Use strong passwords
  3. Combine with SSL/TLS
  4. Regular password rotation
  5. Audit access logs
  6. Limit failed login attempts
  7. Consider IP whitelisting for sensitive areas

Common Issues

  1. 403 Forbidden: Check file permissions
  2. Authentication loop: Verify .htpasswd path
  3. Password not working: Ensure correct encoding
  4. Config not loading: Check syntax and file location