Authenticating HTTP Users Using htpasswd and .htaccess

November 24, 2011 | By | Reply More

htpasswd is used to create and update the flat-files used to store usernames and password for basic authentication of HTTP users. htpasswd encrypts passwords using either a version of MD5 modified for Apache, or the system’s crypt() routine.

htpasswd returns a zero status (“true”) if the username and password have been successfully added or updated in the password file. htpasswd returns 1 if it encounters some problem accessing files, 2 if there was a syntax problem with the command line, 3 if the password was entered interactively and the verification entry didn’t match, 4 if its operation was interrupted, 5 if a value is too long (username, filename, password, or final computed record), 6 if the username contains illegal characters (see the Restrictions section), and 7 if the file is not a valid password file.

Following steps will guide you to create password protected directories in Apache.

1. Create a password file for user ‘sam’ using htpasswd command

htpasswd -c /home/user/.htpasswd sam

This will create a new file and stores a record in it for user sam. The user is prompted for the password. If the file exists and cannot be read, or cannot be written, it is not altered and htpasswd will display a message and return an error status.

2. Add/modify password for sam

htpasswd /home/user/.htpasswd sam

The user is prompted for the password which will get added to the password file.
In order to implement web based authentication (password protected directories), you need to modify the user’s .htaccess file (if it is not available under the ‘Document Root’ of the user, you need to create it) with the following entries.

AuthType Basic
AuthName “Restricted Access”
AuthUserFile /home/user/.htpasswd
Require user sam

Note: If the webserver has disabled the usage of .htaccess file, you can enable it for the user, by modifying the apache configuration file (httpd.conf). Check for the <Directory> directive for the directory for which you need to enable .htaccess.

Replace,

AllowOverride None

With,

AllowOverride AuthConfig

Tags: ,

Category: WEB SERVER

Leave a Reply

Commenting Policy:
Keywords instead of a real name? Comment gets deleted.
A fake name instead of your real name? Comment gets deleted.
1 liner "thank you" comment or offtopic? Comment gets deleted.
If the comment gets approved, we own all rights to it.
All comments are subject to moderation.