Monday, November 5, 2012

Password Protect a Directory Using htpasswd.

Password protect a directory in apache using .htaccess, so that only users with user name and password can access the website.

In order to set the password protected directory, you need to create a .htaccess with the  below lines

AuthType Basic
AuthName "Restricted Access"
AuthUserFile
Require user 


 And your httpd conf file must contain these lines to make the .htaccess work

Directory
Options Indexes Includes FollowSymLinks MultiViews
AllowOverride AuthConfig
Order allow,deny

For example if you need to protect a directory test, first check the user,group of the apache and change the permissions.

[root@tester ~]# egrep -iw 'User|Group' --color=auto /etc/httpd/conf/httpd.conf
# If you wish httpd to run as a different user or group, you must run
# User/Group: The name (or #number) of the user/group to run httpd as.
#  . On SCO (ODT 3) use "User nouser" and "Group nogroup".
#    suggested workaround is to create a user www and use that user.
#  NOTE that some kernels refuse to setgid(Group) or semctl(IPC_SET)
#  when the value of (unsigned)Group is above 60000;
#  don't use Group #-1 on these systems!
User apache
Group apache
# UserDir: The name of the directory that is appended onto a user's home
# directory if a ~user request is received.
# The path to the end user account 'public_html' directory must be
    # To enable requests to /~user/ to serve the user's public_html
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%{User-agent}i" agent
#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
# file in a language the user can understand.

[root@tester ~]# chown apache:apache test
[root@tester ~]# chmod 0660 test


Now you can generate the password using the htpassword for the user. here the user is tester

[root@tester ~]# htpasswd -c /home/tester/password tester
New password:
Re-type new password:
Adding password for user tester

[root@tester ~]# cat /home/tester/password
tester:V8Lg1v0SHqo72

Now you can keep the password file in the same location or different location and make a entry in the .htaccess file. Keep the password file in different location so that it cannot be accessible by the user when viewing the website.

.htaccess
AuthType Basic
AuthName "Restricted Access"
AuthUserFile /etc/httpd/conf/password
Require user tester

Here i placed the password file in different location and entered the required user as tester for accessing.

It works!!

You also have the option of deleting the htpasswd user using the below syntax

[root@tester ~]# htpasswd -D /home/tester/password tester
Deleting password for user tester




No comments: