How to protect a directory using .htaccess
August 7, 2009 / Updated: August 7, 2009 / Lena Shore
Filed under: Web Development
Adding Folder Password Protection
Sometimes you need to protect a directory with a login and password. Here is how to accomplish this. You will need ssh access.
- Create or upload a file named: .htaccess in the directory you are wanting to protect.
- Next, you need to create the password file itself using the filename that matches what you put as [passwordfile] in the .htaccess file. Using our example, you would do this using a command prompt and typing:
The .htaccess file should contain the following 4 lines:
AuthType Basic
AuthName "Some Description"
AuthUserFile /[home-directory-full-path]/[passwordfile]
Require valid-user
NOTE: home-directory-full-path: If your domain was example.com, then the third line would read something like:
AuthUserFile home/user/www/domain.com/allowlist
In the above example “allowlist” is the name we’ve chosen for the password file.
htpasswd -c allowlist myuser
Once you’ve done the above step, you will be prompted twice for the user’s password. If you just want to add another user to an existing password file, or change a password for a user already in the file, then leave off the -c option. To learn more about the “htpasswd” command, you can read this documentation page. Also, you can type “htpasswd” by itself to see all the command’s options.
Removing Folder Password Protection
You can delete the .htaccess file from the command prompt by typing:
rm htdocs/www/.htaccess
(where htdocs/www/ was the directory that you put the .htaccess file in to begin with).