Password protect a folder under Drupal with .htaccess

Posted on February 13, 2012


This applies to all versions of Drupal.

Most of the time you’ll want to have Drupal installed with its default .htaccess-file. Among other things, it takes care of building URLs in “clear” format, which is very nice. Unfortunately, it also prevents one using simple .htaccess/.htpasswd protection. That is very easy to fix!

Setting up password protection

There is are a lot of tutorials on how to do this (1, 2, 3). In short, make a directory to be protected, create .htpasswd file and create .htaccess file. Password file should be in somewhere else than in the protected folder or any other public folder. Save .htaccess to protected folder. It might look like this:

AuthUserFile /full/pathto/.htpasswd
AuthType Basic
AuthName “Protected Folder”
Require valid-user

So far we haven’t touched Drupals .htaccess file, which lies in Drupal root.

Add 401 error

To get past Drupals .htaccess, only thing you have to do is to specify 401 error page. 401 is a call for password, but for some reason if an error page for password-calling page is not set, Apache will fall back to file not found 404 error. Learn more about the matter here. Add this to somewhere in Drupal .htaccess file:

ErrorDocument 401 /401.html

Suite /401.html to your needs. Format above points to a file called 401.html placed in Drupals root folder. That file must exist there, though it does not really matter what is inside it because normally it is not opened. If a wrong password is typed in password dialogue, this page will be shown, but normally you don’t want to be very specific on this kind of error. So you can create a nice html page with 401 error message or just do:

touch ~/pathto/401.html

to create an empty file. Once 401.html file is in right place, Drupal won’t be confused with password protection request made by our password protected folder and will pass the password dialogue through.