- #Written by: Michael Wood
- #Date 12-01-2011
- A very quick and easy way to control directory access is to create an .htaccess file. The .htaccess file contains information to require valid user credentials to access whatever directory you put your .htaccess file in.
- First, we have to create the .htpasswd file. This file contains the username and hash of the password. Example output of the .htpasswd file would look like this:
- user:$apr1$ROvNIWjo$96bOcy.gSiVuMlD9jphYO.
- user2:$apr1$ROvNIWjo$96bOcy.gSiVuMlD9jphYO.
- user3:$apr1$ROvNIWjo$96bOcy.gSiVuMlD9jphYO.
- To creat the file run this command:
- sudo htpasswd -c .htpasswd <username>
- It will ask you for a password.
- To add users to an existing .htpasswd file:
- sudo htpasswd .htpasswd <username>
- Again, it will ask you for a password
- I usually create a directory outside my document root (where my web sites are stored) called user-access
- So, in my case the document root is located at /data/www
- I will create the directory user-access in /data
- Run this command:
- sudo mkdir /data/user-access
- Ok. Remember above when we created the .htpasswd file? Move it to the new directory you just created /data/user-access
- If I had created the file in my home directory it would be something like this:
- sudo mv /home/user/.htpasswd /data/user-access
- Now we are going to create the .htaccess file. I want to restrict users from accessing a download directory on my server. The directory in question is:
- /data/www/downloads
- I'm going to change to this directory and create the .htaccess file:
- cd /data/www/downloads
- Create the .htaccess file:
- sudo vi .htaccess
- Here is an example of what mine looks like:
- AuthUserFile /data/user-access/.htpasswd
- AuthName "Restricted Access - Valid User Credentials Required"
- AuthType Basic
- Require valid-user
- Order allow,deny
- Satisfy any
- The line AuthUserFile /data/user-access/.htpasswd this is telling the .htaccess file where to look for the .htpasswd file we created earlier. It won't work if you don't set this file path correctly.
- The line AuthName "Restricted Access - Valid User Credentials Required" anything wrapped in quotes can be changed to whatever you decide.
- The line Requre valid-user is simply just saying it will accept any user you created with the .htpasswd file. If you want to restrict it to just a single user, you can change that line to Require user <username> (without brackets)
- Restart Apache (this command will differ from the particular Linux distribution you have installed):
- sudo /etc/init.d/apache2 restart
- You can use this .htaccess file to pretty much control access to any web directory now. No need to modify anything in it, just move it to whatever directory you want to control access to.

