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.
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.
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>
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
Save the file and close it, then restart your apache server to implement the change.