Password protecting directories with htaccess
Apache allows access to directories to be restricted unless overridden by a valid user name and password. Here you will see how to set it up in your config file, how to create the .htaccess file, and how to generate the password file for it.
Denying access in httpd.conf
The first step is to deny access to the directory in the httpd.conf file. To do this the following must be added for the directory, or the default to deny access.
Options Indexes FollowSymLinks
The above will deny access to the secret_dir and only allow it to be accessed if the person gains authorization by entering a username and password. We will set this up next.
At this point you need to restart Apache since changes were made the config file, so use
# apachectl graceful
Creating an .htaccess file
The htaccess file specifies how a visitor can get authorized to access the directory. It is normally set up in the following way
AuthName "My Secret Directory" AuthType Basic AuthUserFile /usr/local/www/htaccess/.mypassfile Require valid-user
AuthName is the text shown above the password prompt when the directory is accessed. AuthUserFile points to where you have the password file stored, it can be placed anywhere as long as it is secure.
Generating the password file
Now that we have restricted access, set it so that only users who have a valid username and password can get in we need to set up some users. To do this we will be using htpasswd. When creating a new file the -c flag needs to be used with the location of the file we are writing following. The next argument is the user we are adding.
# htpasswd -c /usr/local/www/htaccess/.mypassfile joe New password: Re-type new password: Adding password for user joe
In the above example we are creating a new password file called .mypassfile in the location we set above in the .htaccess, and are adding the user joe to it. Once you put in this command you will be asked for the password, and to confirm it.
To add another user to the same file we can use the same command without the -c
# htpasswd .mypassfile kelly New password: Re-type new password: Adding password for user kelly
For more options on encryption run htpasswd with the -h flag
# htpasswd -h Usage: htpasswd [-cmdpsD] passwordfile username htpasswd -b[cmdpsD] passwordfile username password htpasswd -n[mdps] username htpasswd -nb[mdps] username password -c Create a new file. -n Don't update file; display results on stdout. -m Force MD5 encryption of the password. -d Force CRYPT encryption of the password (default). -p Do not encrypt the password (plaintext). -s Force SHA encryption of the password. -b Use the password from the command line -D Delete the specified user.
If everything was done successfully a password prompt will come up when you try to access the protected directory, and you will only be allowed in if you enter a correct username and password from the password file.