How to Set Up HTTP Basic Authentication in Nginx

Problem

HTTP Basic Authentication is a simple authentication mechanism built into the HTTP protocol. It requires users to provide a username and password to access certain resources. This guide will walk you through setting up HTTP Basic Authentication in Nginx to secure your web applications.

Solution

  1. Step 1: Install the Apache Utils Package

    sudo apt-get update
    sudo apt-get install apache2-utils
    sudo yum install httpd-tools
  2. Step 2: Create a Password File

    sudo htpasswd -c /etc/nginx/.htpasswd username
    sudo htpasswd /etc/nginx/.htpasswd additionaluser
  3. Step 3: Configure Nginx to Use the Password File

    server {
        listen 80;
        server_name your_domain.com;
    
        location / {
            auth_basic "Restricted Area";
            auth_basic_user_file /etc/nginx/.htpasswd;
            
            proxy_pass http://your_backend_server;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
  4. Step 4: Test the Configuration

    sudo nginx -t
    sudo systemctl reload nginx

Conclusion

HTTP Basic Authentication provides a straightforward way to protect web resources by requiring a username and password. By following these steps, you can easily set up HTTP Basic Authentication in Nginx to enhance the security of your web applications.