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
- Create a Password File
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
-cflag! It will overwrite the existing file.
htpasswd /etc/nginx/.htpasswd anotherusername
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.
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
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
.htpasswdfile 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.