This brief tutorial shows students and new users how to use Apache2 utils to generate basic password authentication for Apache2 directories. This feature can be used to protect directories and restrict access to only authorized users. It’s a great feature and can be used to add a layer of protection to existing directories. To protect Apache2 directories with basic password authentication, the steps below are a great place to start:

Install Apache2 HTTP Utility

Apache2 utility package is easy to install. To install, run the commands below

Create a .htpasswd file

Now that you’ve installed Apache2 utils, run the commands below to create a password file for users. The commands below will prompt you to create a new password for the username specified and store the file in the directory defined. /etc/apache2/.htpasswd Replace myusername with the username you wish to use. You can choose any directory to save the htpasswd file. however, you must specify the location when configuring Apache2. After running the commands above, a new hidden passwd file for the username you selected will be saved in the /etc/apache2/.htpasswd file. Below is the output of the command:

Protect Apache2 Directories

Now that the password file is created, use the highlighted code block below to protect an Apache2 directory. Apache2 default site configuration file is at /etc/apache2/sites-available/default Add these lines below to the directory you want to protect. Save the file. Every time you attempt to browse to the /Private directory, you should get a basic HTTP authentication prompt to type a username and password. To protect the entire Apache2 site, define the root location to protect:  /var/www/html Example: Save the file. The next time you browse the domain, you will be prompted as shown below. That’s it! You may also like the post below: