HTTP Basic Auth is the quickest way to lock a staging environment or /admin behind a password. Create the password file, then point Nginx at it.
Create the user file (installs with apache2-utils / httpd-tools):
sudo htpasswd -c /etc/nginx/.htpasswd alice # -c creates the file (omit -c to add more users)
# prompts for a password; stores a bcrypt/apr1 hash
Protect a whole site:
server {
listen 443 ssl;
server_name staging.example.com;
auth_basic "Restricted — staging";
auth_basic_user_file /etc/nginx/.htpasswd;
location / {
# ...
}
}
Or just one path:
location /admin/ {
auth_basic "Admin only";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://127.0.0.1:3000;
}
Notes:
- Only use it over HTTPS — Basic Auth sends the password base64-encoded (not encrypted) on every request.
auth_basic off;in a nested location turns it back off for an exception (e.g. a public health-check path under a protected prefix).- To allow your office IP without a password but require it for everyone else, combine with
satisfy any:
location /admin/ {
satisfy any;
allow 203.0.113.0/24; # office network: no password
deny all; # everyone else...
auth_basic "Admin only"; # ...must log in
auth_basic_user_file /etc/nginx/.htpasswd;
}
satisfy any passes if either the IP allow rule or the password matches; satisfy all (the default) requires both.
sudo nginx -t && sudo nginx -s reload