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

One should note that 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

  1. Connect to the Mason Cluster via SSH
  2. Enter the following command:
    cd /usr/local/htdocs/your_directory_path
    (Replace your_directory_path appropriately. For instance, if your site is located at www.gmu.edu/departments/english, your_directory_path would be departments/english)
  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

  4. First, we’re going to create the file that will hold the usernames and passwords. Enter the following command:
    /usr/local/apache/bin/htpasswd -c .htpasswd username
    (Replace username with whatever username you’d like. Keep in mind that it’s case sensitive.)
  5. To add more users, simply run the command again, without the -c flag:
    /usr/local/apache/bin/htpasswd .htpasswd username
  6. Now we will create the file that ensures the directory is protected. Enter the following command:
    pico .htaccess
  7. This will put you into 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. For multiple users, just add more lines to the Limit block, like so:

    <Limit GET>
    require user username1
    require user username2
    </Limit>
    
  8. Save the file (Ctrl+O) and exit (Ctrl+X).
  9. Make sure permissions on your .htaccess and .htpasswd files are set to 644.

That should do it. Try accessing the directory through a web browser. If it’s properly setup, you should get a login prompt, and be able to login with one of the usernames you created.

Last Updated: June 4, 2014