How to Use htpasswd for Apache User Credentials?

The htpasswd utility is a command-line tool used to create and update the flat-files used to store usernames and passwords for basic authentication of Apache HTTP users. This article provides a comprehensive guide on how to manage these user credentials, covering how to create new password files, add or update users, delete user accounts, and verify existing passwords. By mastering these fundamental htpasswd commands, system administrators can effectively restrict access to specific directories on an Apache web server.

Creating a New Password File and Adding a User

When you are setting up Apache basic authentication for the first time, you need to create a password file. The -c flag is used to create this file. If the file already exists, using this flag will overwrite it, so it should only be used for the initial setup.

sudo htpasswd -c /etc/apache2/.htpasswd username

After running this command, you will be prompted to enter and confirm the password for the specified user.

Adding or Updating an Existing User

To add a new user to an already existing password file, or to update the password of an existing user, omit the -c flag. Running the command without it will safely append a new user or modify the password of the specified user without erasing other accounts.

sudo htpasswd /etc/apache2/.htpasswd username

Verifying a User’s Password

If you need to verify whether a user’s password is correct without changing it, you can use the -v flag. This is helpful for troubleshooting authentication issues.

htpasswd -v /etc/apache2/.htpasswd username

Deleting a User Account

If a user no longer requires access to the secured directory, you can remove their credentials from the password file using the -D flag.

sudo htpasswd -D /etc/apache2/.htpasswd username

Specifying Encryption Algorithms

By default, modern versions of htpasswd use secure encryption, but you can explicitly define the encryption method if required by your server configuration.

sudo htpasswd -B /etc/apache2/.htpasswd username

Utilizing the Credentials in Apache

Once the .htpasswd file is configured, you must instruct Apache to use it by updating your virtual host configuration file or a local .htaccess file within the directory you want to protect.

AuthType Basic
AuthName "Restricted Access"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user