Restrict Access With Apache – The Mini How To

This is not meant to be a comprehensive how-to on Apache’s authentication systems, rather a practical approach for anyone needing to quickly restrict access to a directory. Apache is an extremely robust web-server, therefore there are many methods for authentication. For ease, I’ll be focusing on Basic Authentication because most of the other type are semantically the same, just syntactically different. Since I have access to the httpd.conf file, I’ll be making my changes there rather than using a .htaccess file.

For this example let’s say I want to protect a directory called privateData. Although your files may be in other locations, my files are located here:

Directory to protect: /var/www/htdocs/privateData
httpd.conf: /etc/apache/conf/httpd.conf
The first thing to do is create a password file with the command “htpasswd”. We’ll call it .passwds. Notice it begins with a “.” (a period). This is because Apache, as a security feature, will not serve up any pages that begin with a period. Create a directory called “passwords” to store the .passwds file.

[root@milkbar html]#mkdir /etc/apache/conf/passwords

Next you use the “htpasswd” command to create the .passwds file. The user I want to have access to the “privateData” directory is called “Durango”.
Note: Only use the “-c” (create) switch the first time you add a user or you’ll create a new file and loose all entries previously added!

[root@milkbar html]#htpasswd –c /etc/apache/conf/passwords/.passwds durango

Apache will need to be able to see this file so give it appropriate permissions or change ownership to the Apache user, which is probably something like “apache” or “www-data”.

[root@milkbar html]#chown -R www-data:www-data /etc/apache/conf/passwords

You will be prompted for your password twice.
Now find and open your httpd.conf file. We will add the following stanza to it:

<Directory “/var/www/htdocs/privateData”>
AuthName “My Private Data”
AuthType Basic
AuthUserFile /etc/apache/conf/passwords/.passwds
require user durango
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order deny,allow
Allow from all

Now save your changes and restart Apache, the method depends on your install/version, but should be something like:

[root@milkbar html]#/etc/init.d/apache restart
[root@milkbar html]#service httpd restart

Testing it out

Open a web browser and navigate to your newly protected directory. You should now be prompted for your user name and password. Please note that Basic Authentication should be used in conjunction with SSL so passwords are not sent over the wire in plain text. If SSL isn’t desirable, use Digest authentication. You can now add more users and or groups to your .passwds file to grant access to others, but this is out side of the scope of this article.