Apache Password protecting a Directory
Password protecting a directory in Apache means that a username/password prompt will appear if someone trys to access any of the files in that directory, or that directory itself. They don’t have to do it every time they load a new page, if you for instance have an application in the directory, as it creates a session and saves the fact they authenticated themselves.
To set this up, add the following into your apache site. Most likely it will be the sites-available/default
<Directory /path/to/directory/to/protect/>
AuthType Basic
AuthName “restricted”
AuthUserFile /path/to/auth/file/authfile.txt
require valid-user
<Directory>
AuthType Basic
AuthName “restricted”
AuthUserFile /path/to/auth/file/authfile.txt
require valid-user
<Directory>
To explain the parts:
- Basic – Means that they have to put in a username/password. Or you could make a request with it in the URL.
- AuthName “xxx” – This is just the name the user sees when they’re given the prompt. You can call it whatever you want.
- AuthUserFile – This is a file with username and password pairs in it. You can set it up without a file like this, but I tend to use the files because you can store the files in a non web root directory. The username/password pairs have to encoded, so to make life easier, head of to http://www.thejackol.com/scripts/htpasswdgen.php. They have a great tool to generate the contents of the auth file.