← All articles
Apache

Creating or Updating Users in htpasswd File

Apache HTTP Server can protect a website, directory, or other resource with HTTP authentication. One common approach is to store usernames and password hashes in a file managed by the htpasswd command-line utility.

This article focuses on credential-file management: creating the file, adding users, changing passwords, and removing users. Apache configuration that consumes the credential file is a separate step.

Security note: Avoid routinely operating as the root user. Use an account with only the permissions required to manage the credential file, protect the file from unauthorized reads or writes, and ensure the credential file is not placed inside a publicly served web directory.

For the examples below, assume the credential file is:

/etc/.apache_users

Create the Credential File and First User

Use htpasswd with the creation option when the file does not yet exist:



htpasswd -c /etc/.apache_users user1
New password: 
Re-type new password: 
Adding password for user user1
View original Gist ↗

The creation flag is important here, but it must be used carefully. If the target file already exists, creating it again can overwrite the existing credential database.

Add Another User

When the credential file already exists, add the new user without recreating the file:



htpasswd /etc/.apache_users user2
New password: 
Re-type new password: 
Adding password for user user2
View original Gist ↗

Important: Do not use the -c option when adding a user to an existing credential file. The option creates a new file and can truncate an existing one, removing previously configured users.

Change an Existing User's Password

Run htpasswd for the existing username and provide the new password when prompted:



htpasswd /etc/.apache_users user2
New password: 
Re-type new password: 
Updating password for user user2
View original Gist ↗

Remove a User

Use the delete operation to remove a username from the credential file:



htpasswd -D /etc/.apache_users user2
Deleting password for user user2
View original Gist ↗

Operational Considerations

The credential file is security-sensitive configuration. Limit filesystem permissions, keep it outside the document root, and avoid exposing its contents in logs, repositories, backups with broad access, or troubleshooting output.

For internet-facing systems, also remember that HTTP Basic authentication does not itself encrypt network traffic. Use TLS/HTTPS so credentials are protected in transit.

Next Step

Once the credential file is ready, Apache must be configured to use it for the protected resource. See Securing a Website Hosted with Apache Web Server for the next part of the configuration.