Blog | G5 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.

htpasswd /etc/nginx/.htpasswd anotherusername
  • Configure nginx
  • 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.

  • Test Your Configuration
  • 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
  • Access the Protected Area
  • 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

    Exit mobile version