Skip Navigation

Password Protect a Directory with .htaccess

Password protecting a directory can be done several ways. Many people use PHP or ASP to verify users, but if you want to protect a directory of files or images (for example), that often isn't practical. Fortunately, Apache has a built-in method for protecting directories from prying eyes, using the .htaccess file.

In order to protect your chosen directory, you will first need to create an .htaccess file. This is the file that the server will check before allowing access to anything in the same directory. That's right, the .htaccess file belongs in the directory you are protecting, and you can have one in each of as many directories as you like.

You'll need first to define a few parameters for the .htaccess file. It needs to know where to find certain information, for example a list of valid usernames and passwords. This is a sample of the few lines required in an .htaccess file to begin with, telling it where the usernames and passwords can be found, amongst other things.

  1. AuthUserFile /full/path/to/.htpasswd
  2. AuthName "Please Log In"
  3. AuthType Basic

You've now defined a few basic parameters for Apache to manage the authorisation process. First, you've defined the location of the .htpasswd file. This is the file that contains all the usernams and encrypted passwords for your site. We'll cover adding information to this file shortly. It's extremely important that you place this file outside of the web root. You should only be able to access it by FTP, not over the web.

The AuthName parameter basically just defines the title of the password entry box when the user logs in. It's not exactly the most important part of the file, but should be defined. The AuthType tells the server what sort of processing is in use, and "Basic" is the most common and perfectly adequate for almost any purpose.

We've told apache where to find files, but we've not told it who, of those people defined in the .htpasswd file, can access the directory. For that reason, we still have another line to define.

If we want to grant access to everyone in the .htpasswd file, we can add this line ("valid-user" is like a keyword, telling apache any user will do):

  1. require valid-user

If we want to just grant access to a single user, we can use "user" and their username instead of "valid-user":

  1. require user dave

A normal and complete .htaccess file might look like this:

  1. AuthUserFile /home/dave/.htpasswd
  2. AuthName "Dave's Login Area"
  3. AuthType Basic
  4.  
  5. require user dave

Now we have almost everything defined, but we are still missing an .htpasswd file. Without that, the server won't know what usernames and passwords are ok.

An .htpasswd file is made up of a series of lines, one for each valid user. Each line looks like this, with a username, then colon, then encrypted password:

  1. username:encryptedpassword

The password encryption is the same as you'll find in PHP's crypt() function. It is not reversible, so you can't find out a password from the encrypted version. (Please note that on page 2 of this article is a tool to help you generate an .htpasswd file, that will help you encrypt passwords).

A user of "dave" and password of "dave" might be added with the following line:

  1. dave:XO5UAT7ceqPvc

Each time you run an encryption function like "crypt", you will almost certainly get a different result. This is down to something called "salt", which in the above case was "XO" (first two letters of encrypted password). Different salt will give different encrypted values, and if not explicitly specified will be randomly generated. Don't worry though, the server is quite capable of understanding all this - if you come up with a different value for the encrypted password and replace it, everything would still work fine, as long as the password was the same.

Once you've created your .htpasswd file, you need to upload it to a safe location on your server, and check you've set the .htaccess file to point to it correctly. Then, upload the .htaccess file to the directory you want to protect and you'll be all set. Simply visit the directory to check it is all working.

.htpasswd Generator

The .htpasswd file needs encrypted passwords, which can be a problem for anyone without experience with a programming language. For that reason, I've created this simple tool, which, if you enter the username and password you wish to use, will generate the appropriate line to add to your .htpasswd file.


will be restored.

45 comments

Good job, as always...
but the topic is very old and covered of articles.
one appoint:
file .htpasswd isn't a special file and can be renamed like any other file. Just set the correct value in the .htaccess
Thanks Dapuzz.

Yup, the .htpasswd can be named anything at all.

The topic is well covered indeed. This happened to come up on the forums today though and I remember there being a lot of articles that went into too much detail, and ones that assumed too much knowledge, so I decided to add one to the over-populated pile.

Plenty of more interesting articles on the way, though - work has been hectic recently and I've got about 12 articles almost-finished, just need to get them polished and examples added etc ... :)
Great! Thank you.

Could you share the Password Generator PHP Script? I have tried many others but they don't work.

Regards,
Chris
United Kingdom #4: June 14, 2005
Hm - No mention that windows/unix seem to use different forms of encryption.
 United States #5: June 23, 2005
Are you saying that everyone that comes into the password protected directory has to use an encrypted password?

"The .htpasswd file needs encrypted passwords, which can be a problem for anyone without experience with a programming language."
Alper
Turkey #6: August 30, 2005
You can use the htpasswd tool to create password. it comes with apache.
At first, things went all well, but when I enter my password in the passwordfield, nothing happens and after three times i get the following error:

'Authorization Required
This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.'

Can any of you tell me what I did wrong...?
No, no, no!

Don't confuse htaccess with password-protection. The purpose of htaccess is to enable users to configure apache locally for their own directories, when they have no privilege to do so in httpd.conf.

noodl
(Sorry, I realise this article is old, but like many others it's perpetuating a myth.)
Per H
Sweden #9: June 8, 2006
The error in #7 that the browser enter the *correct* password and still fails, and the access is not even logged, can be due to a web proxy / cache server inbetween that messes up the communication.

I had this error with a squid proxy and apache server behind. I never tracked the error down, instead I made a workaround by bypassing the webcache by tunneling the web access over ssh directly to the apache server.
It has takes me like 6 hours to find the problemn on a XP PC
United Kingdom #10: June 11, 2006
Try entering this into the .htpasswd file:
java:java

Then go into the password protected directory i.e. 127.0.0.1/protected/

which should bring the login up then type java as the username and java as the password if this works the problem is the encrypted password.

when I use an normal text password in the .htpasswd file it all works, but when I encrypt the password it dont work....

Hope this helps.
in turkish: Sağol kardeş Allah razı olsun valla sabahtan beri arıyodum bunu herkes yazmış ama bir sürü safsata.. sen gerçekten kısa ve öz yazmışsın kalemine sağlık...
in english: Thanks for this article. because ı have searched about .5 day..everybody hs write something but everything that all is free and nothing.. you ve written simple and very clearly...
Matx
Malaysia #12: July 19, 2006
Thanks !!! This is helpful..especially for a newbie like me
Great article. Simple, concise, and it just works.

Thanks a bunch.
oncle camille
Unknown #14: November 23, 2006
great tutorial, thx a lot
Really good tutorial! thx
Excellent starter resource for htaccess. Its of note that in Apache2 the htpasswd program has not only been renamed htpasswd2, but performs and extra function on top of the old set that htpasswd came with, name a -D flag which allows you to delete the specified user from the file.

We recently migrated a whole pile of sites from an Apache 1.3 box to an Apache 2, and found that the old htpasswd files didn't work on the new Apache2 htpasswd2 based mechanism, perhaps there is a different salt in place, or a better crypt algorithm, the end result is that you need therefore to redo any password file ported from an older system

best wishes

Steve
 United States #17: February 22, 2007
This article saved my butt!
Hi,

Here is the code to crypt passwords :
<?php
if($go!="")
{

$saltLength = '2';
$saltChars = '0123456789'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'abcdefghijklmnopqrstuvwxyz';

$salt = "";

for ($index = 1; $index <= $saltLength; $index++) {
$randomNumber = rand(1,strlen($saltChars));
$salt .= substr($saltChars,$randomNumber-1,1);
}

$ligne="$login:".crypt($password,$salt);
<INPUT TYPE=\"text\" VALUE=\"$ligne\">
echo "Copy the pass to insert to htpasswd: <INPUT TYPE=\"text\" VALUE=\"$ligne\">

";
}
?>
MJ
Unknown #19: June 10, 2007
If you are using Apache2 make sure the following is included in the httpd.conf file

AllowOverride AuthConfig

instead of

AllowOverride None
What function do you use to encrypt the password? I'd like to know...

Thanks


Regards,
Anders Moen
leon
United Kingdom #21: July 19, 2007
crypt - One-way string encryption (hashing)

string crypt ( string $str [, string $salt] )

info: http://php.net/crypt
Everything works perfectly fine, on win2k you just have to type username:password in plain text without encrypting anything.

...but how to log OFF? :>
I believe there's no way to really 'log off' and there's no need to.

Its like a one-time-authorization until you time out or something.
Thnx for the write-up. For the windows side of the house, check out: http://www.groovypost.com/howto/apache/password-protect-apache-website/
 Serbia And Montenegro #25: September 1, 2007
Thanks Dave,

I just managed to protect an area of my site using your instructive tutorial.

Regards,
Olga
Thanks, handy helpful tool.
Well I never, a fellow Brightonian.
I cant for the life of me figure out why this wont work for me. ive tried it over and over again and i just cant get it to work. it askes me for a username and pass but when i enter mine in, it doesnt work...tried encripted pass and non encripted pass. still doesnt woek. help?

Thanks, Semp
Sjowhan
Netherlands #29: October 14, 2007
Thanks for the explanation!
nev
United Kingdom #30: November 8, 2007
What's with Vincent Bray? Yes yes yes! Since .htaccess can be used FOR password-protection, then what's the "confusion"?
Jonathan
Unknown #32: November 14, 2007
Im having the same problem as #28. I've tried everything I can think of and read at least 20 tutorials on the subject so far but no matter what I do when I enter my username and password it tells me the password is incorrect. Please someone help.
It seems to me that the encryption can be server-specific. I could not get passwords to work until I put a password-encryption page on my site's server: http://www.virtualfulcrum.net/projects/Web/godaddy_passwd.php
Jonathan
Unknown #34: November 15, 2007
I created my .htaccess and .htpasswd files following the instructions found here: (http://help.godaddy.com/article.php?article_id=1641&).

I just tried to use your godaddy specific encryption link #33 but it is still not working...
@nev

There's nothing stopping people from using htaccess files for password protection, of course. My issue is just that many people get confused about two issues in particular: htaccess files are only for password protection, and: to configure password protection you need to use htaccess files. Neither is correct, but very few tutorials point that out. Whenever possible, this kind of configuration should go in the main config file, allowing the server to run faster (no need to look for htaccess files in every directory leading up to the current one for every request), and keeping configuration together in one place.

Maybe No, no, no! was overdoing it :-)
realety
United States #36: January 7, 2008
Finally a password generator that works! :) Thank You!
Albert
Unknown #37: January 25, 2008
Tried this tutorial. Didn't work at all.......
Wonder why it doesn't. Not even a pop-up menu apears.

gr,

Albert
Judie Schechter
United States #38: January 26, 2008
The code worked great. But, once I am signed in - it seems I never have to sign in again unless I quit out of the browser and launch it again. It can be hours or days and I am still able to get to the protected file after the initial username and password is input.

Is there a way to set up a timeout feature so that if you are away from the page for 10 minutes (for example) then you have to sign back in?
Alan
Unknown #39: February 5, 2008
"In general, you should never use .htaccess files unless you don't have access to the main server configuration file. There is, for example, a prevailing misconception that user authentication should always be done in .htaccess files. This is simply not the case. You can put user authentication configurations in the main server configuration, and this is, in fact, the preferred way to do things."

The Apache Software Foundation.


This doesn't work by default; the server admin has to edit httpd.conf to allow it.
So I'm confused ... was #8 saying htaccess does not really protect directories or just that it isn't the preferred way of doing it. I found this article by googling "how safe is htaccess for password protection." Now that I re-read it, I'm thinking he meant the latter, but I'm just not sure.
Appreciative Mark
Unknown #41: July 8, 2008
Thanks. This help me a lot!
Thanks everyone.

Judie: I'm sorry, but I don't know of any way to do that with htaccess authentication.
 Tennessee, US #43: August 29, 2008
Bravo! Well written and fully explained, your service is greatly appreciated!
Thanks for that informations...
You explained this well enough so event I could understand it!
Thanks so much ;)

Post Your Comment

· Comments with keywords instead of a name have their URLs removed.
· Your email address will not be displayed or shared.

Live Comment Preview

 United States #46: 1 minute ago