Password Protect a Directory Using .htaccess
Protecting files on your website from unauthorized users can be very important. Even more important is the method by which you accomplish this task. You could use PHP to listen for login authorization information on each page, but that doesn't protect your images, documents, and other media, does it? That's why I've found the .htaccess
method of protecting files and directories the most reliable. Oh, and it's easy too!
The system requires two files -- the .htaccess
file and .htpasswd file
.
The .htaccess Code
AuthType Basic AuthName "restricted area" AuthUserFile /home/davidwalsh/html/protect-me-dir/.htpasswd require valid-user
The above code protects a directory called "protect-me-dir" at root level. The "AuthUserFile" value is always specific to your hosting configuration. If you don't know what the value should be, do a phpinfo()
and find the DOCUMENT_ROOT
value.
The .htpasswd Code
davidwalsh:daWHfZrDLB88. rodstewart:roFulYxC2.8ws cssexpert:csmnmq.M8T5ho
The .htpasswd
file contains the usernames and passwords of allowed users. One per line. The passwords are MD5'd for security purposes.
To generate encrypted passwords for your .htpasswd
file, you can use my .htaccess password generator.
I am going to go out on a limb here and say that you are a rod stewart fan. :)
Btw, you can store sensitive documents in a folder that isn’t browsable by Apache and have php authenticate it before the user can download. I wrote an artile about that on my blog.
@Mark: Share the link!
From the Apache documentation:
Security
Make sure that the AuthUserFile is stored outside the document tree of the web-server. Do not put it in the directory that it protects. Otherwise, clients may be able to download the AuthUserFile.
In your example, I would suggest moving .htpasswd to something like ‘/home/davidwalsh/protect-me-dir.htpasswd’.
Well I didn’t want to be the guy that posts his links every where :) so I just mentioned it, but since it is relevent here you go.
http://www.marksanborn.net/php/download-files-through-authentication/
@JP: Good tip!
Hello, I am very new at this and honestly need to know exactly how to do this. Do you know a step by step process. I do not want to upload into my website until I have tested it on my local machine
Scenario, I have an HTML file that I open within a folder, however I want to simply require a password before can view it. Nothing really critical, just want to keep the masses out.
If I put the .htaccess file in that directly, and the .htpasswd in the same directory, how will that keep me from accessing the html file. when that is what I need to click on to test. am I missing something here? Does the index.html on the server automatically look for this password file?
Anything would be great. or maybe you could direct me to a fully laid out example
Thank you for your time
Paul
Hi David,
Really like this nifty little feature – but unfortunately everything seems to work fine except that the password is not accepted. I have tried several alternatives – all with the same result. Any tips on what I need to check will be much appreciated!
Cheers
Simon
Hi,
I did this and I think my path was incorrect. However, when I try to do the PHP info, it is requiring a password–which I can’t do because my path is wrong. How do I remove the .htaccess and .htpassword from my site to fix them? They are not showing up as files in the directory.
Thanks,
Levana
Simply delete the .htaccess file you’ve created.
You’ve probably already worked it out.
I figured it out–just in case anyone reads this: you have to set your FTP client to “show hidden files.”
How do I able to protect and organize the files in directory?
how do I able to protect and organize the filies in directory?
I have used your your info above and it works well. Thank you. How do I prevent the password from being cached or held in cookies? When I log into the web browser it has the info and logs right in.
Thank you, Jeff
@Simon: I have the same issue.
can this crash the apache server? or depending on the server settings a failed access (3+tries) denies you acces to the ENTIRE server??. using this on a server that i get acess to host webpages. but don’t know the intricate security settings of the server? it connects slowly when it works, and if the wrong password denies me for x period of time. from any site that the server hosts. not just my section!! any able to explain this?
I take it that this only protects a directory and not a specific folder?
Awesome blog! :) I was just looking around for some tips of password protection.. and this is neat! I didn’t realize I was already using it by cPanel! :P
Anyways, love the effects you’ve done on your logo.. and the social links that can be dragged anywhere!! One question: HOW did you do that!!!!!!!!!! :O :D
This is great, is it possible to specify which html file opens depending on which username is used to log in?
can we also make an easy ‘ logout’ button???
thx!
I am trying to password protect a subdirectory on an FTP that is already inside of a password protected directory, but the folder becomes hidden as soon as I add in the .htaccess and .htpasswd files. Is there a line of code I can add to the .htaccess file to keep the subdirect visible?
Thanks in advance.
I’m using this code in one of my directories but once I enter the URL and get the pop-up box and enter my UN/ PW it gets stuck in a continuous loop asking me to enter un/pw again and again. Help! Thanks!
Bryan,
I had the same problem. You can’t just use the password that you want to use into .htpasswd. You have to use the ‘htaccess password generator’ link that David has provided first. In that link you’ll enter your proposed username and password and it will spit out a MD5 user and password that you will enter into your .htpasswd file. Upload that to the folder you want to protect and it should work. Good luck!
Jeff Reese,
In order to have the username/password dialog box reappear, you need to close all your browser windows down and restart a new browser session after which the login window will appear again. Even if you clear you cookies, etc. the dialog box will not reopen.
Proxybox, thank you. I made the same mistake as Bryan.
still trying to get this to work. for some reason night working in my sub directory
how do i allow access to certain directories. (how do i turn off the rewrite function)
Unfortunately it did not work for me, already follow proxyboy suggestion but no password work for me. any work around to make it work?
I couldn’t get this to work on my local web server, then I realised that httpd.conf contained the line
AllowOverride None
which was stopping Apache look at the .htaccess file. I changed it to
AllowOverride All
althoughAllowOverride AuthConfig
would have been sufficient.Thanks … it is very easy to use it and remove it as well as :)
carry on good task :)
hello. pretty cool. but it worked the 1st time for me but then after i typed in my username and pw i get this error. and when i delete it and start fresh i get the same error.
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, admin@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
I have the same problem… did you find a way to fix that?
to Michele:
You need to put the .htaccess inside the directory which you want to protect. And you move the .htpasswd “outside” of your whole site web : apache will still be able to find it when authenticating, but it will also prevent users using the website to download it (as it’s now “outside” the web hierarchy).
ex:
1) create your /home/demo/public_html/demo_directory/.htaccess : [to protect demo_directory+everything underneath it]
2) create your
/home/PRIVATE/.htpasswd
with lines made of “username:hashedpasswords”(hashedpasswords are created using one of the tools. it is NOT the password in clear! (never!) )
Hope this helps
i can get this to work it just hangs on the loading and still asks for the login and password.
AllowedOverride All
hashed the username and pw using your link.
im not sure how to get this to work
any suggestions?
hi David. Thank you for your awesome web site. I have a little challenge for you. How it is now, you can assign 100+ users and passwords and all of them end up at the same index page. Is there a way to assign or redirect each line of usern. and passw. to a specific page.
Example: lets say that 3 people have access to the log in password protected site, each person has a custom username and password, but if #1 logs in, it redirects #1 to the site welcome #1 , if #2 logs in, it redirects #2 to the site welcome #2 etc.
Hope you can help us on that. thank you.
i figured it out after hours of trying. here it is. exchange x and y with your files and users
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /var/chroot/home/content/path/path/html/path/.htpasswd
require user x
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /var/chroot/home/content/path/path/html/path/.htpasswd
require user y
DirectoryIndex x.html y.html
add as many as you like
hope this helps.
sorry this makes more sense.
AuthType Basic
AuthName “Restricted Area”
AuthUserFile /var/chroot/home/content/path/path/html/path/.htpasswd
require user x
AuthType Basic
AuthName “Restricted Area”
AuthUserFile /var/chroot/home/content/path/path/html/path/.htpasswd
require user y
DirectoryIndex x.html y.html
sorry it does not post correctly. ill try to explain.
as you know each command must be on its own line. example: “AuthType Basic” on its own line “AuthName restricted area” on its own line etc….
Put “Files x.html” wrapped in beginning code tag on its own line before “AuthType Basic”.
And put “Files ” wrapped in end code tag after “require user x”. Now create a new line and repeat with user “File y.html” wrapped in beginning code tag followed by a new line of “AuthType Basic” followed by “AuthName “Restricted Area””
, “AuthUserFile /var/chroot/home/content/path/path/html/path/.htpasswd” , “require user y” ,and put “Files ” wrapped in end code tag after “require user y” etc..
hope you understand, sorry about my crappy posting attempts :(
i put .htaccess file in /var/www and .htpasswd in /var and tried below code.But after all therse step i am not getting even a prompting widow. i restarted apache and changed premission for files too…but nothing seems to be working.– ;( plese help.
AuthName “My Password-Protected Area – Authorized Users Only”
AuthType Basic
AuthUserFile /var/.htpasswd
require user secretuser
Using our free w3easyProtect script should be quite an easy way to password protect any web directory. Hopefully…;)
Hi
Nice post bust isnt it possible to protect the main folder and then leave a subfolder unprotected?
Nice post, I’d like to protect my private directory in sub domain, is it will work well??
This has been very useful for me! thanks a lot buddy
If anyone is still struggling with this try using dynamic drive .htaccess banning located below.
http://tools.dynamicdrive.com/password/
one question, if i protect the root folder with this, will all the installation be secured? is it inherited to subfolders?
Yes, it is inherited for subfolders.
Hi David,
Great tutorial for the more advanced, however I think it’s important to mention to avoid confusion for newbies that the .htaccess file needs to be in the same directory you are protecting and not the root for example which is somewhat assumed in your explanation. You also should specify that you can’t type in the encrypted password, but instead have to type in the original password you used in the generator. Small nuances, but very important. Thanks!
Very true, at first I got confused using the password generated.
Hi,
nice post, But i have an doubt on that post. i need to add htaccess and htpassword protection for a specific directory on my site. I have tried this below code . but its taking the whole site as password protected .
AddType application/x-httpd-php52 .php52 .php
AuthName “Secure Area”
AuthType Basic
AuthUserFile /home/demo/public_html/demo_directory/.htpasswd
require valid-user
————-
Now i need to add password for demo_directory folder only. so pls help me.
Thanks,
mmkiyan.
you should revert what you did, I guess.
You need to put the .htaccess inside the directory which you want to protect. And you move the .htpasswd “outside” of your whole site web : apache will still be able to find it when authenticating, but it will also prevent users using the website to download it (as it’s now “outside” the web hierarchy).
ex:
1) create your /home/demo/public_html/demo_directory/.htaccess : [to protect demo_directory+everything underneath it]
2) And you create your /home/PRIVATE/.htpasswd file (containing lines made of “username:hashedpasswords”)
Please note that hashedpasswords are created using one of the tools. It is NOT the password in clear! Just the corresponding hash. (never have passwords in clear in a file!)
Hope this helps
to mmkiyan : you should revert what you did, I guess.
You need to put the .htaccess inside the directory which you want to protect. And you move the .htpasswd “outside” of your whole site web : apache will still be able to find it when authenticating, but it will also prevent users using the website to download it (as it’s now “outside” the web hierarchy).
ex:
1) create your /home/demo/public_html/demo_directory/.htaccess : [to protect demo_directory+everything underneath it]
2) create your /home/PRIVATE/.htpasswd with lines made of “username:hashedpasswords”
(hashedpasswords are created using one of the tools. it is NOT the password in clear! (never!) )
Hope this helps
Is there a way to retrieve the username of the logged user?
I used your password generator to create two passwords a month ago. They continue to work perfectly. Trying to add a third and it doesn’t work as it doesn’t find a match. I’ve changed sequence in the password file, changed the password to remove special characters and even numbers, validated spelling and case but the problem persists. I’ve confirmed that the file on the server is the correct file and it continues to work for the old passwords.
Any suggestions welcomed.
Maybe any blanks or line breaks too many in the .htaccess file?
You might also try this pw generator:
http://w3easy.org/online-tools/password-generator.php
On your instructions, how do i “Do a
phpinfo()
“.I have no idea what this means, where to go, or how to do it/
how do you create the .htpasswd file?
I created .htaccess with notepad then deleted .txt
when I create .htpasswd with notepad and attempt to delete the .txt I get an error that I must type a file name.
what method are others using to create the file?
Hi,
I tried all the steps as suggested. On accessing the accessory, I am prompted for a username and password. But, after I enter the username and password, I get a 500 internal error message!! I tried checking the error log through the cpanel, but there are no errors logged in. Kindly help.
Regards
Vikrant
I can’t get this to work in AWS EB (Amazon Web Services ElasticBeanstalk).
I’m not network pro. I’m a front end dev with very basic knowledge of networking/ftp/aws.
I’d like to password protect a file and/or directory after spinning up an AWS EB server.
I initially get prompted for user/pwd but then it goes to “Internal Server Error.” I can’t figure out why.
Anyone have experience with htacess/htpasswd and AWS EB?
Thank you!!
Thank you so much David. It worked
An
.htaccess
file is a way to configure the details of your website without needed to alter the server config files. Thanks for sharing codes. I want to confirm that can we use this to access server side settings configuration that allows the.htaccess
file to override standard website configs:I have always generate
.htaccess
file with online.htaccess
password generator tool. As I am newbie for this so need detailed knowledge.I am looking forward.