The .htaccess file provides a way to make configuration changes on a per-directory basis. This file can contain one or more configuration directives. These directives will then be applied to the directory in which the .htaccess file exists and all its subdirectories.
Follow the steps outlined below to protect a directory with .htaccess and htpasswd. The example server used below is CentOS/RHEL.
1. Use htpasswd password utility to create username/password combinations independent of the system login password for web page access.Specify the location of the password file, and if it does not yet exist, include a -c , or create switch on the command line. Replace username with the users to be created.
# htpasswd -c /etc/httpd/conf/.htpasswd username
For adding other user do not use -c option again.
# htpasswd /etc/httpd/conf/.htpasswd username
2. Make the .htpasswd file readable by all users. Depends whether to give read access to all or not.
# chmod 644 /etc/httpd/conf/.htpasswd
3. Create a .htaccess file in the directory (e.g /var/www/html/test) to which password control has to be applied with these entries. Below is a sample .htaccess file :
# cat .htaccess AuthUserFile /etc/httpd/conf/.htpasswd AuthName "Restricted" AuthType Basic require user username
Remember this password protects the directory and all its subdirectories.
– The AuthUserFile tells Apache to use the .htpasswd file.
– The require user statement tells Apache that only user “username” in the .htpasswd file should have access. If all .htpasswd users must have access, replace this line with “require valid-user“.
– AuthType Basic instructs Apache to accept basic unencrypted passwords from the remote users Web browser.
4. Set the correct file protections on the new .htaccess file in the directory (/var/www/html/test). Give file permissions as per requirement.
# chmod 644 /var/www/html/test/.htaccess
5. Make sure /etc/httpd/conf/http.conf file has an AllowOverride statement in a directive for (/var/www/html/test).
# cat /etc/httpd/conf/http.conf <Directory "/var/www/html/test"> AllowOverride AuthConfig </Directory>
6. Restart Apache.
# service httpd restart
7. Try accessing the web site http://newsite.com/test/test.html and it will prompt for a password.