All about basic authentication
Basic authentication prompts visitors for a username and password before they can access a virtual host — or a specific part of one.
This article explains the three pieces involved (htpasswd file, htpasswd users, basic authentication realm), the same-UNIX-user requirement, and the Apache-vs-nginx difference in how you scope the protected area.
The three pieces
- Htpasswd file — a credentials file owned by a UNIX user. Holds one or more user/password pairs.
- Htpasswd users — entries inside the htpasswd file. Each has a username and a password.
- Basic authentication realm — the link that attaches an htpasswd file to a virtual host, with a name (shown in the browser's auth prompt) and an optional scope.
Set them up in that order: create an htpasswd file, add htpasswd users to it, then attach the file to a virtual host via a basic authentication realm. For the click-by-click steps, see Set up basic authentication.
Same UNIX user requirement
The htpasswd file and the virtual host must belong to the same UNIX user. A realm can't bridge across UNIX users.
This is a security constraint — credentials shouldn't be readable by a different user's processes.
Scoping: Apache vs nginx
How you restrict basic auth to part of a virtual host depends on the server software.
Apache — Directory Path
For Apache virtual hosts, set 'Directory Path' on the realm. It's relative to the virtual host's document root.
null— protect the entire document root./admin— protect/adminand everything under it.
nginx — URI Path
For nginx virtual hosts, set 'URI Path' on the realm. It's matched against the request URI.
null— protect the entire virtual host./admin— protect any URI starting with/admin.
Set whichever applies to the virtual host's server software; leave the other one null.
Multiple realms on one virtual host
A virtual host can have multiple basic authentication realms — useful when different parts of the site need different credentials, or when one area should be open and another locked.
Use cases by target group
- Web agencies — protect a client staging site behind a single htpasswd file. Give the client one username and password, swap them when the project hands over. If you'd rather restrict by IP than by password, see firewall groups on the domain router.
- Tech agencies / SaaS — wrap a sub-path like
/adminor/metricswhile leaving the rest of the application public. Combine with the application's own login as a second layer — if the application's auth has a bug, basic auth is still in front of it. - Shops — keep a pre-launch storefront behind basic auth so staff and the agency can preview against real product data without it being indexed.
Reserved directives
When a virtual host has any realm attached, the auth_basic and auth_basic_user_file nginx directives are reserved by the realm system. Don't set them in the default context of the virtual host's custom config — the realm manages them.