Protecting a directory using .htpasswd and .htaccess


Recently I wanted to restrict the access to a directory in one of our server via web, the easiest solution found was to achieve it through the use of a .htpasswd and a .htaccess file. Following are the steps used to achieve this.

Creating .htaccess file

Navigate to the directory required to provide the rescricted access via Internet and create a file .htaccess using one of your favorite editor

AuthType Basic
AuthName "Website Site with Restriced Access"
AuthUserFile /path/to/folder/required/restricted/access/.htpasswd
AuthGroupFile /dev/null
require valid-user

Creating .htpasswd file

This file will holds the allowed login credentials to content inside the restricted access folder.

$ htpasswd -c /path/to/folder/required/restricted/access/.htpasswd
$ Enter Password:
$ Re-enter Password:
$ New user added successfully

In the first command htpasswd -c will create a new file called .htpasswd in the specified location. To add more users simply issue htpasswd command without -c

Enabling Apache mod_rewrite

Use locate to find if the mod_rewrite.so is available on your server.

$ sudo updatedb
$ locate mod_rewrite.so

It will found in /usr/lib/apache2/modules

New apache follow some folders to enable and disable mods. So now do this:

$ cd /etc/apache2/mods-enabled
$ vim rewrite.load (you may use any editor to edit this file)

Now paste this following line

LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so

Then edit /etc/apache2/sites-available/default or /etc/apache2/sites-available/000-default (check which one available on your system). Find the following

Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

and change it to

Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all

Finally restart Apache

$ sudo /etc/init.d/apache2 restart
or
$ sudo service apache2 restart

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: