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.
AuthUserFile /full/path/to/.htpasswd
AuthName "Please Log In"
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):
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":
require user dave
A normal and complete .htaccess file might look like this:
AuthUserFile /home/dave/.htpasswd
AuthName "Dave's Login Area"
AuthType Basic
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:
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:
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.

84 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
#1, Dapuzz, Italy, 15 March 2005. Reply to this.
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 ... :)
#2, Dave Child, United Kingdom, 15 March 2005. Reply to this.
Great! Thank you.
Could you share the Password Generator PHP Script? I have tried many others but they don't work.
Regards,
#3, Liem, Viet Nam, 28 May 2005. Reply to this.
Hm - No mention that windows/unix seem to use different forms of encryption.
#4, Chris, United Kingdom, 14 June 2005. Reply to this.
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."
#5, Michael, United States, 23 June 2005. Reply to this.
You can use the htpasswd tool to create password. it comes with apache.
#6, Alper, Turkey, 30 August 2005. Reply to this.
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...?
#7, Tommy, Netherlands, 13 October 2005. Reply to this.
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.)
#8, Vincent Bray, United Kingdom, 23 May 2006. Reply to this.
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.
#9, Per H, Sweden, 8 June 2006. Reply to this.
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.
#10, It has takes me like 6 hours to find the problemn on a XP PC, United Kingdom, 11 June 2006. Reply to this.
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...
#11, Alparslan Koç, Turkey, 19 June 2006. Reply to this.
Thanks !!! This is helpful..especially for a newbie like me
#12, Matx, Malaysia, 19 July 2006. Reply to this.
Great article. Simple, concise, and it just works.
Thanks a bunch.
#13, NIck J, France, 17 November 2006. Reply to this.
great tutorial, thx a lot
#14, oncle camille, Unknown, 23 November 2006. Reply to this.
Really good tutorial! thx
#15, eduardo, Unknown, 14 January 2007. Reply to this.
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
#16, Steve Nisbet, United Kingdom, 25 January 2007. Reply to this.
This article saved my butt!
#17, jb, United States, 22 February 2007. Reply to this.
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\">";
}
?>
#18, Tiger, Unknown, 21 March 2007. Reply to this.
If you are using Apache2 make sure the following is included in the httpd.conf file
AllowOverride AuthConfig
instead of
AllowOverride None
#19, MJ, Unknown, 9 June 2007. Reply to this.
What function do you use to encrypt the password? I'd like to know...
Thanks
Regards,
Anders Moen
#20, Anders Moen, Norway, 16 July 2007. Reply to this.
crypt - One-way string encryption (hashing) string crypt ( string $str [, string $salt] ) info: http://php.net/crypt
#21, leon, United Kingdom, 19 July 2007. Reply to this.
Everything works perfectly fine, on win2k you just have to type username:password in plain text without encrypting anything.
...but how to log OFF? :>
Replies: #78.
#22, Pytak, Poland, 25 August 2007. Reply to this.
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.
#23, Keehun Nam, Unknown, 28 August 2007. Reply to this.
Thnx for the write-up. For the windows side of the house, check out: http://www.groovypost.com/howto/apache/password-protect-apache-website/
#24, MrGroove, United States, 28 August 2007. Reply to this.
Thanks Dave,
I just managed to protect an area of my site using your instructive tutorial.
Regards,
Olga
#25, Olga, Serbia And Montenegro, 1 September 2007. Reply to this.
Thanks, handy helpful tool.
#26, Adam Khan, United Kingdom, 5 September 2007. Reply to this.
Well I never, a fellow Brightonian.
#27, Adam Khan, United Kingdom, 5 September 2007. Reply to this.
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
#28, Semp, Canada, 30 September 2007. Reply to this.
Thanks for the explanation!
#29, Sjowhan, Netherlands, 14 October 2007. Reply to this.
What's with Vincent Bray? Yes yes yes! Since .htaccess can be used FOR password-protection, then what's the "confusion"?
#30, nev, United Kingdom, 8 November 2007. Reply to this.
more informations :
http://httpd.apache.org/docs/2.0/howto/htaccess.html
#31, LoLo, France, 12 November 2007. Reply to this.
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.
#32, Jonathan, Unknown, 14 November 2007. Reply to this.
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
#33, gld, United States, 14 November 2007. Reply to this.
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...
#34, Jonathan, Unknown, 15 November 2007. Reply to this.
@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 :-)
#35, Vincent Bray, United States, 20 November 2007. Reply to this.
Finally a password generator that works! :) Thank You!
#36, realety, United States, 7 January 2008. Reply to this.
Tried this tutorial. Didn't work at all.......
Wonder why it doesn't. Not even a pop-up menu apears.
gr,
Albert
#37, Albert, Unknown, 25 January 2008. Reply to this.
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?
#38, Judie Schechter, United States, 26 January 2008. Reply to this.
"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.
#39, Alan, Unknown, 5 February 2008. Reply to this.
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.
#40, Sean, Unknown, 1 March 2008. Reply to this.
Thanks. This help me a lot!
#41, Appreciative Mark, Unknown, 8 July 2008. Reply to this.
Thanks everyone.
Judie: I'm sorry, but I don't know of any way to do that with htaccess authentication.
#42, DaveChild, United Kingdom, 8 July 2008. Reply to this.
Bravo! Well written and fully explained, your service is greatly appreciated!
#43, Noah, Unknown, 29 August 2008. Reply to this.
Thanks for that informations...
#44, seo españa, Spain, 8 October 2008. Reply to this.
You explained this well enough so event I could understand it!
Thanks so much ;)
#45, Oregon guy, Unknown, 3 November 2008. Reply to this.
Just try this and it works well... thanks for the clear instruction and online tool!
#46, Jack, New York, 21 November 2008. Reply to this.
I love this article, it can help me to understand the htaccess function.
Thanks, a lot of helpful info
#47, Joanne, Malaysia, 29 November 2008. Reply to this.
This is the best article ever!!, it's simple and it works!! Thanks for sharing this knowledge dude...
#48, Pervert Angel, Indonesia, 11 December 2008. Reply to this.
It seems you can forever access the folder on the same computer as long as the cache is not cleared. Is it possible to kill the session (or whatever it's appropriately called in this context) or limit it for only a few hours?
#49, Nelson, Philippines, 14 January 2009. Reply to this.
THANK YOU THANK YOU THANK YOU!
Very easily explained and the encryption was great!
#50, Dan, Unknown, 14 January 2009. Reply to this.
Thanks for sharing, it's useful for me
#51, Tori, Malaysia, 29 January 2009. Reply to this.
Great article, thanks.
also thanks to MJ.. i'd never guessed it's not working because of that :)
#52, gs1m, Serbia And Montenegro, 25 February 2009. Reply to this.
just what I was looking for.
thank you.
#53, brian, United States, 24 March 2009. Reply to this.
IMPORTANT! Many Apache installations (especially on Windows) have "AllowOverride" set to "none" in the httpd.conf file. In order for user/password protection to work AllowOverride must be set to "AuthConfig". ALSO, Apache's user/password protection is the weakest possible. Credentials are sent as "clear text" and "protected" files are not encrypted. Don't use this protection method for anything serious !!!
#54, ButterBean, United States, 26 April 2009. Reply to this.
I believe your crypt() function is using DES and not MD5 algorithm. On my version of Apache 2.2.11 your generated password did not work. I googled htpasswd generator and found one that did work. On further investigation of the cryptography algorithms I discovered that this might be system specific. I'm using WindowsXP. Perhaps this is specific to the version of Apache. That I don't know. What I know is that your tutorial worked up until the password generator.
#55, Nicholas Juntilla, Unknown, 22 May 2009. Reply to this.
Hi
Greate tutorial
I have a question ...( Ialway have one)
If I have 6 users with 6 differenf folders and I liket ot make sure that user A cannot get to a folder of user C and so on
Do I have to incert .htaccess with indivigual namn in every forlder?
Or it is a way to use this differetly
Thanx
#56, Lev A, Unknown, 4 June 2009. Reply to this.
this is not working on vista
#57, Amila, Sri Lanka, 1 July 2009. Reply to this.
Does anybody know how to make it so that instead of looking for the password in the .htpasswd file in looks in a mysql Database?
#58, Michael Gutierrez, United States, 17 August 2009. Reply to this.
I've been looking for an explanation about this for 2 hours before I finally came upon this article. You did a great job explaining the .htaccess file, NOW I understand. Thanks!
#59, Matt Salsbury, Unknown, 23 August 2009. Reply to this.
Nice tutorial.
I made a simple script that uses the linux htpasswd command to manage users in a htpasswd file
Note it only works on linux and you need to put this probably inside the protected dir just so nobody can access it.
<?php
# Set to path of the .htaccess file
$AuthUserFile = '/etc/apache2/.htpasswd';
if (isset($_GET['action'])) {
switch ($_GET['action']) {
case 'delete':
exec('htpasswd -D '.$AuthUserFile.' '.$_GET['user']);
break;
case 'add':
exec('htpasswd -b '.$AuthUserFile.' '.$_REQUEST['user'].' '.$_REQUEST['pass']);
break;
}
}
?>
<pre>
<?php
$htpasswd = file($AuthUserFile);
foreach ($htpasswd as $line) {
$Credentials = explode(':', $line);
echo '<a href="'.$_SERVER['PHP_SELF'].'?action=delete&user='.$Credentials[0].'">X</a> '.$Credentials[0]."\n";
}
?>
</pre>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?action=add" method="post">
<input type="text" name="user" /> : <input type="text" name="pass" /> <input type="submit" value="Add" />
</form>
#60, Moonbox, United States, 29 August 2009. Reply to this.
I've implemented this and I understood that if I set up .htaccess in a directory, it also applied to any sub-directories.
I'm able to use the password, access files/pages in the directory that contains .htaccess but when I try links from those pages with target="_blank", it asks for the password again and then doesn't like the password.
Can anyone help me solve this problem? I do not want to ask for the password again once a user has access to the initial protected directory.
Thanks!!
#61, Diane, USA, 30 August 2009. Reply to this.
This is great... thanks for the htpasswd generator.
#62, Abe, Boise, ID, 2 September 2009. Reply to this.
Hi, I am a bit lost in what all to do? can someone help me please?
#63, Mason, United States, 26 September 2009. Reply to this.
I have a question this worked prefectly on my linux machine. However when I transfered the settings nothing wanted to work. I recived a password missmatch. Appriciate you feedback
#64, J, Malta, 20 October 2009. Reply to this.
htpasswd generator isn't working :(
#65, Kuroki Kaze, Russia, 18 December 2009. Reply to this.
Thank you for this tutorial. It was very helpful. My setup was for a WAMP server so all I had to do was pop the .htaccess file into the www directory.
#66, James, 28 January 2010. Reply to this.
WOW, perfect tutorial. Also thanks for the generator too!
#67, Frank Conry, Thailand, 2 March 2010. Reply to this.
The generator doesn't work, 404 error.
#68, Adrian, 2 March 2010. Reply to this.
After trying every tutorial online (including this one), I found that my problem is that my .htpasswd needs the actual passwords, and not the encrypted version. Anyone know why this might be different than everyone else's apache server, and how I can fix it? (I'm using Windows and Apache 2.2)
#69, Ariel Jacobs, USA, 9 April 2010. Reply to this.
You can create the password file with "htpasswd -c /path/to/file/file user"
#70, Guilherme, Brazil, 2 June 2010. Reply to this.
Thanks for the great tutorial, Dave! And thanks for the command line generator, Guilherme!
#71, fisherwebdev, USA, 28 July 2010. Reply to this.
Hi mate wow youre a brightoner?? same. good stuff. just wondered if you can help me out on something:
For the site http://www.dramaticmoments.co.uk I am trying to make a password
protected page, whereby multiple passwords and user names can be set up
(around 100) for the following page:
http://www.dramaticmoments.co.uk/index.php/the-course
At the moment there is only one, and this doesnt prove to be very safe. Is
there a decent wordpress plugin????If you're using WordPress to create the
page, I'm not sure if a .htaccess file will do the trick because WP uses
URL-rewriting and you'd be locking out only one page. Maybe it's possible to
use a .htaccess file to password-protect a page depending on its query string
parameters. .htaccess files are beyond me a im very new to all this.
Are there plugins or can .htaccess be achievable please let me know asap! thanks.
#72, Josh White, uk, 6 August 2010. Reply to this.
Tried this and now i am less prone to hack attempts.
#73, Alberto Douglas, United States, 25 August 2010. Reply to this.
this allows only one time to login and to login again you must close the browser and reopen the browser.
#74, Magson Fernandes, United States, 7 September 2010. Reply to this.
I have applied same procedure to protect my directory but when i open website, it directly open instead of Prompt for user name and password. Do i need to do some thing extra. immediate answer will highly be appreciated
#75, Azhar, pakistan, 29 December 2010. Reply to this.
Very sorry this took so long to fix. Procrastination is not my friend. The generator is back up and running now though.
#76, DaveChild, United Kingdom, 20 January 2011. Reply to this.
I can't stress enough how much of a bad idea this is. .htaccess files were never intended for use on production servers. They exist for the multi-user webserver environment (where your document root is at domain.com/~username), so that the users had the option of doing things like this.
If you run a webserver, put this stuff in the httpd.conf or the virtual server config files. .htaccess cripples apache!
#77, _lynks, uk, 1 March 2011. Reply to this.
#22
What do you mean by that comment about windows server 2000?
There is several levels of authentication methods that could be used, from basic authentication, digest authentication, kerberos (domain account), etc.
so they cover from totally insecure to completely secure (certificate based) ones.
Had to check so that i don't say total bull..
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/36ea667e-c578-43b5-87fa-a2f174efb27a.mspx?mfr=true
W2k was basically the same as W2k3 in that manner.
Yeah, i found that too.
http://msdn.microsoft.com/en-us/library/ms954300.aspx
BTW. I didn't get this linux thing working. :D
I guess that it is not possible to use in all free web space hosts etc..
#78, jyrki. MCSE 2003, Finland, 26 March 2011. Reply to this.
Great tutorial nice and clear - thanks! I notice Dave and Dapuzz say the file can be renamed, which it can, but apparently it is best to keep .ht at the beginning of the password filename so it is prevented from being displayed by Apache setup. This explained it:
http://corz.org/serv/tricks/htaccess.php
#79, Steve, UK, 3 October 2011. Reply to this.
You can use htpasswd to generate encrypted passwords IF you have access to htpasswd, which is not always the case on, say, some shared hosts. (like godaddy, as an example).
#80, tony, usa, 1 December 2011. Reply to this.
is there any way to just block direct access to teh directory without a password?
#81, Elijah Clark, US, 8 December 2011. Reply to this.
having an issue, can I place the files in the same folder?
#82, Elijah, 30 December 2011. Reply to this.
also, is there a difference between blocking a file and directory?
#83, Elijah, 30 December 2011. Reply to this.
Vast tutorial nice and clear - thanks! I notice Dave and Dapuzz say the file can be renamed, which it can, but it seems that it is best to keep .ht at the beginning of the password filename so it is barred from being display by Apache setup.
#84, --, NY, 2 February 2012. Reply to this.