Hostwinds Tutorials
Search results for:
Table of Contents
Setting up password authentication for a website can be crucial in sharing content with authorized users. This is discussed (using a few nifty .htaccess rules) in Password protect files or directories with .htaccess. However, you may wonder how these credentials are validated and where they are stored, and the answer to that is in the .htpasswd file, as discussed next.
A .htpasswd file is typically used when protecting a file, folder, or entire website with a password using HTTP authentication and implemented using rules within the .htaccess file. User credentials are stored on separate lines, with each line containing a username and password separated by a colon (:). Usernames are stored in plain text but passwords are stored in an encrypted hashed format. This encryption is usually MD5, although, in Linux, it can be based on the crypt() function. Although it is possible to name the password file to whatever you want, this is not advised as Apache is preconfigured to use .htpasswd by default; and dot files (files that begin with ".") are generally hidden files.
For Linux, you can create a .htpasswd file using the htpasswd command (which is generally available only after a web server has been installed).
First, you'll need to have a username in mind. For this example, I have chosen the username bob123. Next, you'll need to be logged in to your server via SSH. If you're not certain how to access your server via SSH, please review the following article: Connecting to Your Server via SSH. Finally, you'd execute the following command. Please be aware that if you are executing this as a non-root user, you'll need to use sudo at the beginning of the command line (note that the -c option creates the .htpasswd file and overwrites it if it already exists):
htpasswd -c /home/usernamehere/.htpasswd bob123
You'll be prompted to provide and confirm a password for this user. If you'd like to add additional users, you can do by repeating the prior command. For example:
htpasswd /home/usernamehere/.htpasswd nancy456
If you were to check the contents of the .htpasswd file, you would see something similar to the following:
bob123:$apr1$FaPCZHMe$jYiw5.9UevKx25pBH4AsT/
nancy456:$apr1$mrCHcVhc$oNdJeRcWKPk2z8dlzQI0x/
The value after the user name is the encrypted version of the user's password. With this in mind, you can create a relatively simple script that automatically adds a user's credentials to the .htpasswd file upon creation and/or approval.
Written by Michael Brower / June 22, 2017