protect

How to password protect a website or directory using .htaccess and .htpasswd

07/07/2025

Password-protecting a website or a specific folder is an effective way to restrict access. This can be easily done using the .htaccess and .htpasswd files in Apache. The .htaccess file controls access, while the .htpasswd file stores usernames and hashed passwords.

Creating a .htpasswd File

The .htpasswd file contains user credentials in the following format:

username:hashed_password

Since storing passwords in plain text is insecure, we should hash them using a secure algorithm such as MD5 or bcrypt. You can generate a hashed password using an online service such as htpasswd generator. Once created, save the .htpasswd file in a safe location, preferably outside the root folder.

Configuring .htaccess to require authentication

To password protect an entire website or a specific folder, create (or edit) a .htaccess file in that directory and add the following lines:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
  • AuthType Basic will enable basic authentication.
  • AuthName is the message that is displayed at the login prompt.
  • AuthUserFile specifies the path to the .htpasswd file.
  • Require valid-user allows access only to users specified in .htpasswd.

Multiple-user permission

You can add multiple users to .htpasswd, each with a hashed password:

user1:$apr1$abcdefg$xyzxyzxyzxyzxyzxyzxyz
user2:$apr1$1234567$abcdefghijklmnopqrs

Each user will have their own access credentials.

Protecting a specific folder

To protect only a specific folder, place the .htaccess file in that folder. This ensures that only the folder and its subdirectories are protected.

Verifying access control

After setup, navigate to the protected area in your browser. You should see a login prompt that requires valid credentials.

Removing password protection

To disable password protection, delete or comment out the .htaccess rules.

Using .htaccess and .htpasswd provides a simple yet effective way to restrict access to private sections of your website.

Video tutorial

The video tutorial shows a slightly different setup option

Other articles:

Leave a Reply

Your email address will not be published. Required fields are marked *