Get a Pentest and security assessment of your IT network.

Cyber Security

nginx: Basic Access Control

TL;DR

This guide shows you how to protect parts of your website using nginx’s basic authentication. It’s a simple way to add a username and password before people can see certain pages or directories.

Steps

  1. Create a Password File
  2. nginx uses a special file containing usernames and encrypted passwords. You’ll use the htpasswd command to create this. If you don’t have it, install it (e.g., on Debian/Ubuntu: sudo apt-get install apache2-utils; on CentOS/RHEL: sudo yum install httpd-tools).

    htpasswd -c /etc/nginx/.htpasswd yourusername

    The -c flag creates a new file. You’ll be prompted to enter and confirm the password for the user.

    • Important: If you’re adding more users later, *don’t* use the -c flag! It will overwrite the existing file.
    htpasswd /etc/nginx/.htpasswd anotherusername
  3. Configure nginx
  4. Edit your nginx configuration file (usually found in /etc/nginx/sites-available/default or similar). You need to add a location block that uses the auth_basic directive.

    server {
        ...
    
        location /secret-area { # Replace with the directory you want to protect
          auth_basic           "Restricted Area";
          auth_basic_user_file /etc/nginx/.htpasswd;
        }
    
        ...
    }

    Replace /secret-area with the actual path you want to protect. The text in quotes after auth_basic is what users will see in the login prompt.

  5. Test Your Configuration
  6. Before restarting nginx, check your configuration for errors:

    sudo nginx -t

    If there are no errors, restart or reload nginx to apply the changes:

    sudo systemctl restart nginx
  7. Access the Protected Area
  8. Now, when you try to access /secret-area (or whatever path you configured), a popup window will appear asking for a username and password. Enter the credentials you created with htpasswd.

Important Considerations

  • Security: Basic authentication sends usernames and passwords encoded, but not encrypted, so it’s best used over HTTPS (SSL/TLS).
  • File Permissions: Make sure the .htpasswd file is only readable by the nginx user. A typical setup would be to set permissions to 600: sudo chmod 600 /etc/nginx/.htpasswd.
  • Location Block Specificity: Be careful with your location blocks. If you’re not specific enough, you might accidentally protect more than intended.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation