Nginx can ask for a user name and password before it shows a folder of your website, for example a folder with files for friends or a page only you should see. This page protects the folder /private/ and lets Nginx list the files in it. The commands were tested on Ubuntu 26.04 LTS with Nginx 1.28; run them as root.
You need Nginx: Website With HTTPS on a Linux Server: Nginx and Let's Encrypt. Use HTTPS as described there: with plain http://, the password travels unencrypted.
1. The Password File
Create a user, here alex. openssl asks for the password twice and does not show it:
printf "alex:%s\n" "$(openssl passwd -apr1)" > /etc/nginx/.htpasswd chown root:www-data /etc/nginx/.htpasswd chmod 640 /etc/nginx/.htpasswd
For another user, run the first line again with >> instead of >, so that the file is extended and not replaced. To remove a user, delete their line from the file.
2. The Folder and Its Settings
Create the folder in the web root of your site, for the default site /var/www/html, and put your files into it:
mkdir /var/www/html/private
Open the settings of your site, for the default site nano /etc/nginx/sites-available/default. Inside the server { … } block, above the line location / {, add:
location /private/ {
auth_basic "Private area";
auth_basic_user_file /etc/nginx/.htpasswd;
autoindex on;
}
auth_basicswitches on the password; the text is shown in some browsers' login window.autoindex onlists the files of the folder. Without it, a folder without anindex.htmlanswers403 Forbidden.
Check the settings and apply them:
nginx -t systemctl reload nginx
nginx -t must say syntax is ok and test is successful.
3. Test It
Open https://your-domain/private/. The browser asks for the user name and password, then shows Index of /private/ with your files. From the command line:
curl -I https://your-domain/private/
Without a password, the answer is 401 with WWW-Authenticate: Basic realm="Private area". The folder and each file in it answer 401 without the password and with a wrong one, and 200 with the right one. A wrong password is logged in /var/log/nginx/error.log as user "alex": password mismatch.
Other Places
- The whole site: put the two
auth_basiclines intolocation / { … }instead. - Several protected folders: one
locationblock per folder; they can use the same password file.
Against password guessing on the login, see Protect Your Linux Server With a Firewall and Fail2ban.