How to Password Protect a Directory

On www.gmu.edu it is possible to ensure that web visitors must enter a login and password to access a certain directory.

Security Note

While this technique will prevent most web visitors from accessing the contents of your protected directory, this isn’t a particularly secure method. The password is sent in the clear, and in most cases, anyone who has server access to the Mason Cluster could download your files through SFTP.

Do not rely on this technique to protect confidential information.

Instructions

Step 1

Connect to the Mason Cluster.

Step 2

Enter the following command:
cd /usr/local/htdocs/your_directory_path

Note: Replace your_directory_path appropriately. (e.g., if your site is located at www.gmu.edu/departments/english, your_directory_path would be departments/english)

Step 3

If you have a directory already created for the page(s) that you want to protect, change into that directory:
cd directory_to_protect

Otherwise, create the directory first:
mkdir directory_to_protect
cd directory_to_protect

Step 4

To create the file that will hold the usernames and passwords enter the following command:
/usr/local/apache/bin/htpasswd -c .htpasswd username

Note: Replace username with whatever username you’d like and keep in mind that it’s case sensitive.

Step 5

To add more users run the command again, without the -c flag:
/usr/local/apache/bin/htpasswd .htpasswd username

Step 6

To create the file that ensures the directory is protected enter the following command:
pico .htaccess

Step 7

You are now in a text editor. Copy and paste the following code:
AuthUserFile /usr/local/htdocs/your_directory_path/directory_to_protect/.htpasswd
AuthName "Password Protected Directory"
AuthType Basic

<Limit GET>
require user username
<Limit>

Replace with your own values where appropriate. To add multiple users add more lines to the Limit block:

<Limit GET>
require user username1
require user username2
<Limit>

Step 8

Save the file (Ctrl+O) and exit (Ctrl+X).

Step 9

Set permissions on your .htaccess and .htpasswd files to 644.

Step 10

Test by trying to access the directory through a web browser. If it is properly set up, you should get a login prompt, and be able to log in with one of the usernames you created.