How can I protect a folder with a username and password?

If you are looking at this page, we are assuming you already have the necessary skills to perform these operations. However, if you do not feel confident in your own ability, please feel free to contact RHPCS with your request.

In order to require a username and password to access part or all of a website, you need to do the following:

  1. create a password file outside of your web folder
  2. create a configuration file in the folder to be protected.

Note that htpasswd -c will create a new password file or replace the specified one if it already exists; omit the -c to add a new username to the existing file.

  1. Create a password file (htpasswd)
    1. umask 022
    2. mkdir ~/etc
    3. htpasswd -c ~/etc/htpasswd username_of_your_choice
    4. chmod 711 ~ ~/etc ~/public_html
  2. Create a configuration file to protect the folder (.htaccess)
    1. mkdir -p ~/public_html/folder_to_protect
    2. cd ~/public_html/folder_to_protect
    3. pico .htaccess
      AuthType Basic
      AuthName "Restricted Files"
      AuthUserFile /home/your_username/etc/htpasswd
      Require user username_of_your_choice
      (ctrl-x to save)

If you browse to http://ms.mcmaster.ca/~your_username/folder_to_protect, you should be asked for a username and password.

A few notes:

  • If you have problem to access your protected page/folder you may try to reset your password:
    htpasswd -b /home/your_username/etc/htpasswd username_of_your_choice new-password
  • The two mkdir commands may complain if the directories already exist; don't worry about that.
  • All folders beneath the one with the .htaccess file will also require the username and password.
  • You can add additional usernames with
    htpasswd ~/etc/htpasswd new_username
  • The umask and chmod commands are used to make sure that the password file are readable by the web server.
  • If you wish people to see a list of files in the folder rather than an index page, first run the command:
    chmod 755 ~/public_html/foldername
    ... and then add the following directive to the top of an .htaccess file in ~/public_html/foldername:
    Options +Indexes

For full details, see Authentication, Authorization and Access Control at apache.org.