Sometimes a folder on your website should stay private. It might hold client previews, staging files or premium downloads. In 2011, I showed how to password protect a directory with .htaccess on Apache servers. The method still works. However, my original example stored passwords in plain text, which is no longer acceptable. This updated guide fixes that.

How It Works

Apache reads a file called .htaccess inside the folder you want to protect. That file points to a second file, .htpasswd, which stores usernames and hashed passwords. When someone opens the folder, the browser asks for a username and password. If the login fails, the server returns a 401 error.

Before You Password Protect a Directory

  • Your site must run on Apache, or LiteSpeed, which also reads .htaccess files.
  • You need FTP, SSH or file manager access.
  • Your site must use HTTPS, because basic authentication sends credentials with every request.

Step 1: Create the .htpasswd File

Never type passwords into this file yourself. Instead, generate a hashed entry. On a server with SSH access, run this command:

htpasswd -c /home/youruser/.htpasswd aky

The tool asks for a password and stores it securely hashed. Drop the -c flag when adding more users; otherwise, it overwrites the file. Moreover, keep the file outside your public web folder, so nobody can download it.

No SSH access? Most control panels, such as cPanel, offer a Directory Privacy tool that creates both files for you.

Step 2: Create the .htaccess File

Next, create a file named .htaccess inside the folder you want to protect. Then add these lines:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/youruser/.htpasswd
Require valid-user

The AuthUserFile line must use the full server path to your .htpasswd file. Finally, upload the file and open the folder in a browser to test the login prompt.

Running Nginx?

Nginx ignores .htaccess files completely. Instead, add these directives to the site’s server configuration, or ask your host to do it:

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

A Note for WordPress Sites

Protecting the whole wp-admin folder can break features that rely on admin-ajax.php. Therefore, test carefully, or protect only specific folders. Additionally, back up your existing .htaccess file before editing it. For another quick hardening step, see how to disable directory browsing with .htaccess.

We Are Done!

Your folder now asks for a login before showing anything. Remember, basic authentication is a simple lock, not a complete security system. If you need a proper review of your website’s security, talk to our team in NOIDA.