Nginx Basic Authentication Setup
Protect Nginx locations with HTTP Basic Authentication using htpasswd files. Step-by-step setup guide with password creation and selective protection.
Detailed Explanation
HTTP Basic Authentication adds a username and password prompt to specified locations in your Nginx configuration. It provides a straightforward way to restrict access to staging environments, admin panels, or internal tools.
Creating the Password File
Use the htpasswd utility from the apache2-utils package to create a password file with bcrypt hashing:
sudo apt install apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd admin
The -c flag creates a new file. Omit it when adding additional users to an existing file to avoid overwriting previous entries.
Nginx Configuration
Apply basic auth to a location using the auth_basic and auth_basic_user_file directives:
location /admin {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://backend;
}
The string after auth_basic is the realm name displayed in the browser's login dialog. Setting auth_basic off explicitly disables authentication for a nested location block.
Protecting an Entire Site
To protect all locations at once, place the auth_basic directives in the server block. You can then selectively disable authentication for specific paths that need to remain publicly accessible:
server {
auth_basic "Staging Environment";
auth_basic_user_file /etc/nginx/.htpasswd;
location /health {
auth_basic off;
return 200 "OK";
}
}
This pattern is commonly used for staging environments where the entire site should be protected, but health check endpoints need to respond to monitoring systems without credentials.
Combining with IP Restrictions
For stronger security, combine basic auth with IP-based access control using the satisfy directive to create a layered authentication strategy:
location /admin {
satisfy any;
allow 192.168.1.0/24;
deny all;
auth_basic "Admin";
auth_basic_user_file /etc/nginx/.htpasswd;
}
With satisfy any, users connecting from the allowed IP range gain access without entering a password, while users from all other networks must authenticate with valid credentials. Using satisfy all would require both conditions to pass.
Security Considerations
Basic auth transmits credentials as Base64-encoded text, which provides no encryption whatsoever. Always use it in combination with HTTPS to prevent credential interception by network eavesdroppers. For production-facing applications that handle sensitive data, consider implementing more robust authentication mechanisms like OAuth 2.0 or JWT tokens instead.
Use Case
You need to quickly restrict access to a staging or development environment so only team members with credentials can view the site before it goes live.