Basic authentication puts a browser password prompt in front of a path, before your application is reached. It is ideal for staging sites, an internal tool, or a second lock on an admin area.

Make the password file

sudo apt-get install -y apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd sara      # -c creates; omit it to ADD
sudo chmod 640 /etc/nginx/.htpasswd
sudo chown root:www-data /etc/nginx/.htpasswd
-c overwrites the file. Use it once, and never again on the same file, or you have just deleted every other account in it.

Nginx

location /staging/ {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

Apache and LiteSpeed

AuthType Basic
AuthName "Restricted"
AuthUserFile /etc/nginx/.htpasswd
Require valid-user

What it protects

  • A staging site from search engines and from casual visitors.
  • An admin path from automated login attempts, before they reach your application.
  • Anything you want quietly closed without writing code.

What it does not

  • It is only as private as your TLS. Over http the password is sent in near-plain text on every request.
  • There is no lockout and no log of who logged in - it is a shared password, not an account.
  • It breaks APIs and webhooks that do not know to send credentials. Exempt those paths explicitly.
location /staging/api/webhook {
    auth_basic off;
}
For a staging site, add add_header X-Robots-Tag "noindex, nofollow"; as well. Basic auth already keeps crawlers out; the header keeps it out of the index if the protection is ever removed by accident.