Setting up some form of password authentication for a website can be a crucial part of sharing content with authorized users. In a different article we discuss how to do exactly that using a few nifty .htaccess rules. If you’d like to read more about how this is done you can check out our article, which covers how to Password protect files or directories with .htaccess. However, you may be wondering how are these credentials validated and where are they stored? The answer is with the .htpasswd file, which will be the focus of this article.
What Is .htpasswd?
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 a .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, however 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 whatever you want, this is strongly not advised as Apache is preconfigured to use .htpasswd by default, and dot files (files that begin with “.”) are generally hidden files.
How To Create a .htpasswd File?
Depending on your platform, this can be achieved in a few different ways. The easiest method is to head over to one of the various .htpasswd creation websites and follow their simple instructions to generate the necessary entries for an .htpasswd file. I would recommend the generator offered by htaccesstools.com as it is very simple and to the point, go check it out: Htpasswd Generator. If you’re like me and would like how to see how this is done without using a generator, stick around!
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 note that if you executing this as a non root user you’ll need to use sudo.
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 so via the following:
htpasswd /home/usernamehere/.htpasswd newUser2
If you were to check the contents of the .htpasswd file you should see something similar to the following.
With this in mind, perhaps you could even create a script that adds a user’s credentials automatically to the .htpasswd file upon creation or approval!