How to Password-Protect Admin & Staging Sites with HTTP Basic Auth in Nginx
Before exposing staging websites, Prometheus dashboards, or internal APIs to the public internet, configuring Nginx HTTP Basic Authentication provides a bulletproof first layer of defense that stops unauthorized visitors and search engine crawlers.
Interactive Nginx Config Generator
server {
listen 80;
server_name example.com;
# Enhanced Security Headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
location / {
# Enable basic auth prompt
auth_basic "Restricted Staging Environment";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Allow health checks and webhooks without password
location /api/health {
auth_basic off;
proxy_pass http://127.0.0.1:3000;
}
}Directives & Architecture Explained
auth_basic "Restricted Staging Environment";Enables authentication and sets the prompt realm message displayed in the browser login modal.
auth_basic_user_file /etc/nginx/.htpasswd;Specifies the absolute path to the file containing username and bcrypt/Apache password hashes.
auth_basic off;Selectively turns off authentication for specific sub-paths like health checks, status monitors, or webhooks.
Production Verification & Reload Workflow
sudo apt-get install apache2-utils -yInstall htpasswd utility tool on Ubuntu/Debian
sudo htpasswd -c /etc/nginx/.htpasswd adminCreate new .htpasswd file with user admin and hashed password
curl -u admin:secret http://staging.example.com/Test HTTP Basic Auth credentials via curl CLI
Production Troubleshooting Tips
- β’Ensure the Nginx worker user (usually www-data) has read permission for /etc/nginx/.htpasswd: sudo chmod 640 /etc/nginx/.htpasswd && sudo chown root:www-data /etc/nginx/.htpasswd.
- β’Always serve Basic Auth over HTTPS! On plain HTTP, base64-encoded credentials can be sniffed in cleartext over the network.
- β’To add another user without wiping existing users, omit the -c flag: sudo htpasswd /etc/nginx/.htpasswd developer.
Frequently Asked Questions
How do I create an htpasswd file without installing apache2-utils?
You can generate a password hash with openssl: openssl passwd -apr1 mypassword and append user:hash into /etc/nginx/.htpasswd directly.
Will search engines index password-protected pages?
No. Search engine crawlers (Googlebot) receive HTTP 401 Unauthorized and will not index the content or scrape private staging links.