Password-protect a directory (.htpasswd)

Protect a directory or staging site with .htaccess and .htpasswd – for Apache and nginx, using secure hashing.

A staging version shortly before launch, a preview link for a client, or an admin area without its own login: often a directory shouldn’t be public, but a full user management system would be overkill. That’s what password protection with .htpasswd is for. The web server asks for a user name and password before it delivers a single file – no matter whether WordPress, a Symfony application or static HTML sits behind it.

This guide explains how it works, which hashing method to use and how to set up protection in Apache and nginx. At the end, you’ll find the most common mistakes and their causes.

How password protection works

Under the hood, this is HTTP “Basic” authentication, defined in RFC 7617. When someone requests a protected URL, the server responds with status 401 and the browser shows its login dialog. From then on, the browser sends the header Authorization: Basic … with user name and password on every request.

These credentials are only Base64-encoded, not encrypted. Anyone who can read the connection can turn them back into plain text. Basic Auth is therefore only safe over HTTPS. Always redirect http:// to https:// before the password prompt kicks in.

Two properties are worth knowing: there’s no logout – the browser remembers the credentials until it is closed. And there’s no protection against repeated failed attempts. A long, random password is therefore a must, not a nice-to-have. The Password Generator creates one right in your browser.

A welcome side effect: search engines also receive status 401 and don’t index the pages. For staging environments, that’s exactly what you want, and it’s more reliable than a robots.txt, which is merely a request.

The .htpasswd file and hashing methods

The .htpasswd file contains one user per line, separated from the password hash by a colon:

editor:$2y$10$5LcRexEgEbk0lj2fRj9K2O/e00pwcsJ0WxjfBBlO7rbP1ZilFpnra
client:$apr1$KO67C8Af$SnLrrzsUIDD7LXpbSvoMG.

The server recognizes the method by the start of the hash:

MethodRecognized byVerdict
bcrypt$2y$recommended; Apache 2.4.4 and later, nginx depends on the system
APR1-MD5$apr1$compatible with Apache and nginx, but dated
SHA-1{SHA}unsalted, don’t use it any more
crypt (DES)13 characters, no prefixonly the first 8 characters count, don’t use it any more
Plain text–Apache on Windows only, nginx with {PLAIN}; avoid

You can see for yourself how weak SHA-1 is here: compute the SHA-1 of a password in the Hash Generator with Base64 output, and you get exactly the value after {SHA}. Identical passwords always produce identical hashes, and such checksums can be tried in huge numbers in a short time. bcrypt, by contrast, uses a unique salt for every password and is deliberately slow.

The number after $2y$ is the cost factor. Each step doubles the computing effort. Because the server checks the password on every request – including each image and CSS file – a very high value becomes noticeable. 10 is a good middle ground.

Create the entry with the .htpasswd Generator, which supports bcrypt, APR1-MD5 and SHA-1 and provides matching configuration snippets as well. On the command line, use the htpasswd program from the Apache package:

# create a new file (-c overwrites an existing file!)
htpasswd -c -B -C 10 /var/www/client/.htpasswd editor

# add another user or change a password
htpasswd -B -C 10 /var/www/client/.htpasswd client

# delete a user or verify a password
htpasswd -D /var/www/client/.htpasswd client
htpasswd -v /var/www/client/.htpasswd editor

-B selects bcrypt, -C the cost factor. Without -C, htpasswd uses the low default of 5.

Apache: protection via .htaccess

Put a .htaccess file with this content into the directory you want to protect:

AuthType Basic
AuthName "Staging"
AuthUserFile /var/www/client/.htpasswd
Require valid-user
  • AuthName is the name of the protected area. Some browsers show it in the login dialog.
  • AuthUserFile needs the absolute path in the file system – not the URL, and not a path relative to the .htaccess. A relative path is resolved relative to Apache’s ServerRoot and almost always leads nowhere.
  • Require valid-user lets in any user listed in the file. With Require user editor, you restrict access to specific names.

Store the .htpasswd outside the web root whenever possible, in a directory that can’t be reached via a URL. In these examples, the website lives in /var/www/client/public and the .htpasswd one level above. Apache’s default configuration does block files starting with .ht, but you shouldn’t rely on that. On shared hosting, your provider’s control panel usually shows the absolute path. If not, briefly upload a PHP file containing <?php echo __DIR__; – and delete it afterwards.

If you have access to the server configuration, the same directives are better placed in a <Directory> block. It’s faster, and nobody can overwrite the .htaccess by accident. The Apache authentication documentation has the details.

Protecting individual files

To protect just one file, such as a preview, wrap the directives in <Files>:

<Files "preview.php">
    AuthType Basic
    AuthName "Preview"
    AuthUserFile /var/www/client/.htpasswd
    Require valid-user
</Files>

Exceptions for specific IP addresses

In the office or for a monitoring service, the password prompt is often a nuisance. With Apache 2.4, you can let either condition suffice:

AuthType Basic
AuthName "Staging"
AuthUserFile /var/www/client/.htpasswd
<RequireAny>
    Require ip 203.0.113.10
    Require ip 198.51.100.0/24
    Require valid-user
</RequireAny>

If the server sits behind a proxy or CDN, Apache may only see the proxy’s address. In that case, the real visitor IP has to be determined first, for example with mod_remoteip.

nginx: auth_basic

nginx doesn’t read .htaccess files. The protection goes straight into the server configuration, in the server block or a location block:

location / {
    auth_basic           "Staging";
    auth_basic_user_file /etc/nginx/htpasswd/client;
}

# just one directory, with an IP exception
location /admin/ {
    satisfy any;
    allow 203.0.113.10;
    deny  all;
    auth_basic           "Admin";
    auth_basic_user_file /etc/nginx/htpasswd/client;
}

The file format is the same as for Apache. According to the documentation, nginx understands APR1-MD5, {SHA}, {SSHA} and {PLAIN}, plus anything the operating system’s crypt() function supports. Whether bcrypt works therefore depends on the system: many current Linux distributions support it, but don’t take it for granted. Test the login after setting it up. If bcrypt fails, APR1-MD5 is the compatible fallback.

Important: unlike Apache, nginx does not block files like .htpasswd on its own. If the file sits in the web root, anyone can download it. With nginx, always keep it outside, for example under /etc/nginx/. After changing the configuration, check it with nginx -t and then reload.

Common mistakes

  • 500 Internal Server Error: usually a typo in the .htaccess, a missing .htpasswd or a path Apache can’t find. The server’s error log names the exact cause, such as “Could not open password file”.
  • Relative or wrong path: AuthUserFile .htpasswd doesn’t work. Use the full path starting at /.
  • No password prompt: if AllowOverride None is set for the directory, Apache ignores the .htaccess completely – and the site stays open. You need at least AllowOverride AuthConfig.
  • File in the web root: check whether https://your-domain.com/.htpasswd is reachable. You should get a 403 or 404, never the file content.
  • Wrong permissions: the web server user must be able to read the file. Nobody else should, for example with chmod 640 and the web server’s group.
  • Login “doesn’t work” or won’t go away: the browser remembers the credentials. Test changes in a private window. A typo in the user name also leads to rejected logins – case matters.

Quick summary

  • Use Basic Auth over HTTPS only, with a long, random password.
  • Choose bcrypt with cost factor 10; fall back to APR1-MD5 if nginx has trouble with it.
  • Keep the .htpasswd outside the web root and reference it with an absolute path.
  • Apache: AuthType Basic, AuthName, AuthUserFile, Require valid-user. nginx: auth_basic and auth_basic_user_file.
  • Remove the protection from the live domain at launch, but keep it on the staging environment.

Tools for this topic

More guides