Simple way to protect your Apache website

Simple way to protect your Apache website feature image
Published on Sat Mar 04 2023

My current employer has 4-5 websites that I have to manage and one of which they request I keep it protected. So here is a simple way we can protect our website using htaccess and htpasswd.

To protect your website with .htaccess and .htpasswd, you will need to follow a few simple steps:

First thing is to get into your website’s root directory via SSH. Get your websites file path with pwd as this will be the way you can point where to create the .htaccess file:

~ pwd
/home/username/yourwebsite.com

Now it’s time to create a .htpasswd file with the following command:

htpasswd -c /home/username/yourwebsite.com/.htpasswd user1

Please change the parameters to fit your needs. Change the path to the path we generated in step 2 followed by .htpasswd and the username you would like to use for the login. Once you hit enter, you will be prompted to enter a password.

Navigate to the folder and you should see the .htpassword. The file should contain your username and password. I you wish to create multiple username and passwords, you may do so by following the same format. The format of “username:password” where the two are separated by a colon. The password using the command above is hashed and makes it impossible to decrypt. So my recommendation is to create a username and password with that command. Only issue is the .htpasswd gets rewritten. What you can do is get the contents of the file, run the command with another username and then append the old content into the newly generated .htpasswd file.

user1:theencrytedpassword
user2:anotherencryptedpassword

The next step is to create or edit the .htaccess file in the directory that you want to protect. This file should contain the following code at the top of the file:

AuthUserFile /path/to/.htpasswd
AuthType Basic
AuthName "Restricted Area"
Require valid-user

Everything should be good to go! Your website is now protected with a username and password. Sometimes you might need to give the .htpasswd permission so if you run to any problems run this command:

chmod 644 .htpasswd