How to Set Up Password Protection for Apache

Apache can set up password protection for directories and files using htpasswd and htaccess rules.

Installing Tools

The installation of the needed tools are slightly different for Debian/Redhat based distros.

You will need to have Apache installed to use this guide

Debian/Ubuntu

Run the following command:

sudo apt-get install apache2-utils

Redhat/CentOS

Run the following command:

sudo yum install httpd-tools

Creating the Password Storage File

After installing the tools to be able to create the password, we can then use the tools to be able to create it.

You will want to keep the .htpasswd file in a secure location that is not publicly available.

Run the following code, substituting the path with the location of your choosing and the username you would like to create the password for:

sudo htpasswd -c /path/to/directory/.htpasswd <username>

I used the -c option to create the file, for adding additional users, leave out the -c option

After you run the command, you will receive a prompt to create the password for that user.

Restricting Access

Now that you've created a password file and you've added users, you need to password protect the directories of your choice.

You will create a .htaccess file in the directory that you want to protect with the following command.

touch .htaccess

Once you've created the file, you will use your preferred text editor to add the following lines to the .htaccess file.

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

Make sure to use the same path to the file that you created earlier

Save the file and close it, then restart your apache server to implement the change.