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
- Connect to your server with SSH (a safe way to type commands on a remote computer).
- 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.
- 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.
- 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
- Open the settings file in an editor such as nano:
sudo nano /etc/nginx/conf.d/default.conf
- Inside the
serverblock, add alocationblock 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 /.
- Save the file. In nano, press Ctrl + O, then Enter, then Ctrl + X.
- Test the settings:
sudo nginx -t
This checks for typing mistakes.
- 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.
-c.Quick recap
- Nginx needs the lock in its settings, not in .htaccess.
- Make a password file with
htpasswd. - Add
auth_basiclines to a location block. - Run
nginx -t, then reload.