Sunday, May 24, 2015

Creating a password protected directory in Apache2 server

While working on some assignment preparation for a networking course, I wanted to create a password protected directory inside Apache2 server's webroot directory. Even though this is something straightforward and many people have documented it, still I faced many difficulties while trying to configure it. Therefore I decided to note down the steps for my own future use. So, here we go.

Login to the web server and take the following steps.

cd /var/www/
sudo mkdir test-directory
cd test-directory/
sudo nano protected-file.txt

This is the file which we will protect. For the moment, just enter some text inside this file and save it. Now we create another important file inside this directory as follows.

sudo nano .htaccess

The content of this file should be as shown below. The path should be placed according to where we will place the .htpasswd file in later steps.

AuthUserFile /path/to/our/password/.htpasswd
AuthType Basic
AuthName "My restricted Area"
Require valid-user

Now let's move out and change some access privileges.

cd ../
sudo chmod 777 -R test-directory/

Now we should go to the place we decided to create the password file.

cd /path/to/our/password/
sudo nano .htpasswd

Enter the uname  and password line inside this file. We can use some online tool to generate the content of this file based on the username and password we are going to use. One such an online tool is this. Then let's provide permission for this directory too. Finally we should restart the apache2 server.

chmod 777 -r /path/to/our/password/
sudo /etc/init.d/apache2 reload

Now we can go to the password protected directory using the web browser which will prompt for the username and password before allowing to view the content of that directory.


No comments:

Post a Comment