Password Protecting Directories and Files in Apache

Sometimes you may need to distribute files to various users over the Internet. Instead of giving each user a separate account, it is often easier to put the files on a Web page and use Apache's htpasswd to control the remote access.

Step 1: Create a file named .htaccess in the directory you want to protect.

AuthName "Password protected files"
AuthType Basic
AuthUserFile /home/somewhere/.htpasswd
Require valid-user

Keep the .htpasswd file someplace secure where it is not accessible by a browser. Set its permissions so Apache can read it.

Step 2: Create the new user

cd /home/somewhere/
htpasswd -m .htpasswd username
The '-m' option uses Apache's modified MD5 algorithm to encrypt the password. This will allow the password file to be used with Apache on any operating system.

If the .htpasswd file doesn't exist, use this command instead:
htpasswd -cm .htpasswd username

which will create a new .htpasswd file and delete the old one.

Step 3: Edit httpd.conf

Change the AllowOverride option
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#     
#    AllowOverride None
    AllowOverride AuthConfig Limit

and restart Apache. This only needs to be done once.


Back