All about basic authentication
Basic authentication prompts visitors for a username and password before they can reach a site, or a specific part of one.
This article explains the three pieces involved (htpasswd file, htpasswd users, basic authentication realm), the rule that they all have to belong to the same site, and the Apache-vs-nginx difference in how you limit the protected area.
The three pieces
- Htpasswd file — a credentials file belonging to one site. Holds one or more user/password pairs.
- Htpasswd users — the entries inside that file. Each has a username and a password.
- Basic authentication realm — the link that attaches an htpasswd file to a site. Has a name shown in the browser's prompt, and an optional scope.
Set them up in that order. For the click-by-click steps, see Set up basic authentication.
They all have to belong to the same site
The htpasswd file and the site must belong to the same account. You can't protect one site with credentials that belong to another.
Reason: credentials should not be readable by another site's processes.
Scoping: Apache vs nginx
Which field you use depends on which web server the site runs on. Set the one that applies and leave the other null.
Apache: 'Directory Path'
Relative to the site's document root.
null→ protects the entire document root./admin→ protects/adminand everything under it.
nginx: 'URI Path'
Matched against the request URI.
null→ protects the entire site./admin→ protects any URI starting with/admin.
Multiple realms on one site
A site can have several realms. Useful when different parts of it need different credentials, or when one area should be open and another locked.
Common uses:
- Client staging site — one htpasswd file, one username and password for the client, swapped when the project hands over. To restrict by IP address instead, see firewall groups on the domain router.
- A sub-path like
/adminor/metrics— locked while the rest of the application stays public. Put it in front of the application's own login as a second layer, so a bug in the application's login does not expose the area. - Pre-launch storefront — staff and the agency can preview against real product data, and search engines cannot index it.
Reserved directives
When a site has any realm attached, the realm system manages the auth_basic and auth_basic_user_file nginx directives.
Do not set them in the default context of the site's custom config.