Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

How to Password Protect a Folder with Nginx

This guide shows you how to ask visitors for a username and password before they open a folder on an Nginx server. It needs root access, so it fits a VPS or dedicated server.

How-To Guides2 min read9 steps

What is Nginx?

Nginx (say "engine-x") is software that serves websites to visitors. It reads a settings file to know what to do. We will add a rule there that locks one folder. Nginx does not use .htaccess files like Apache does, so the lock goes in the Nginx settings.

Warning: a mistake in the Nginx settings can stop your site. Back up the file before you edit it.

Steps

  1. Connect to your server with SSH (a safe way to type commands on a remote computer).
  2. Install the tool that makes password files:
sudo apt install apache2-utils

This works on Ubuntu or Debian. On CentOS, AlmaLinux or Rocky use sudo yum install httpd-tools.

  1. Create a password file and your first user:
sudo htpasswd -c /etc/nginx/.htpasswd myuser

It asks you to type a password twice. Change myuser to the name you want. Use -c only the first time, because it creates the file new each time.

  1. Back up your site settings file. The path may differ on your server:
sudo cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.bak
  1. Open the settings file in an editor such as nano:
sudo nano /etc/nginx/conf.d/default.conf
  1. Inside the server block, add a location block for your folder:
location /private/ {
    auth_basic "Private area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

This locks everything under /private/. To lock the whole site, use location /.

  1. Save the file. In nano, press Ctrl + O, then Enter, then Ctrl + X.
  2. Test the settings:
sudo nginx -t

This checks for typing mistakes.

  1. Reload Nginx:
sudo systemctl reload nginx

This applies the change without stopping the site.

Test it

Open yourdomain.com/private/ in a private browser window. A login box should appear.

Tip: To add another user later, run the same htpasswd command without -c.

Quick recap

  • Nginx needs the lock in its settings, not in .htaccess.
  • Make a password file with htpasswd.
  • Add auth_basic lines to a location block.
  • Run nginx -t, then reload.