• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Running a Website / Apache / Password Protecting Your Pages with htaccess

Password Protecting Your Pages with htaccess

3 October 2005 / 35 Comments

Introduction

You may have visited a web page that pops up a dialog box similar to this one:

Password protection dialog

If you don’t know the username and password to enter, then you can’t access the page or site – it’s “password protected”. It’s sometimes handy to be able to password protect your pages like this – for example:

  • You’re building a new site, but you only want yourself (and maybe a select few) to be able to view the work-in-progress.
  • You have an area of your site that you never want the general public to have access to – for example, your web stats or private pages.
  • You have some paid (subscription) content on your site that only subscribers should be able to access.

Apache lets you password protect individual files, folders, or your entire site fairly easily. Read on to find out how it’s done.

How it works

To add password protection to your pages, you need to do the following two things:

  1. Create a text file on your server that will store your username and password.
  2. Create a special file called .htaccess in the folder you want to protect.

That’s it! Now let’s take a look at how to do each step.

Creating the password file

The first step is to create a simple text file that will store your username and password, separated by a colon (:). The small catch is that the password must be encrypted. Luckily, there are many free web-based utilities that will encrypt the password for you. Try one of these:

  • 4WebHelp’s online .htpasswd encryption tool
  • Alterlinks .htaccess password generator
  • htmlite’s htpasswd encryption page

Simply enter your desired username and password in one of these pages and submit the form. You’ll get back a string similar to the following:


fred:p29cmnwl4a0et

Now, open up your favourite text editor (e.g. Notepad or TextEdit), then copy and paste the username/password string into the editor. Save the file and call it .htpasswd.

Next, upload this file to your website. Make sure you place it outside the Web root of your site if possible, as you don’t want just anyone to be able to view the file! For example, place it above your public_html or htdocs folder. (Having said this, Apache is often set up by default to block web-based access to files beginning with .ht. Better safe than sorry though!)

If you can’t place your .htpasswd file outside your Web root, name it something that’s not easily guessable – for example, .htxuymwp – so that people won’t be able to find it easily. (In addition, it helps to start the filename with .ht; as mentioned earlier, Apache usually blocks access to files starting with .ht.)

Alternative: Creating the password file using htpasswd

If you have SSH access to your web server (or you’re running Apache on a local machine), you can encrypt your password and add it to your password file in one go by using the htpasswd utility that comes with Apache. Simply SSH to your server or open up a terminal window on your local machine, cd to the folder where you want to create your password file, and type:

htpasswd -c .htpasswd fred

(where fred is the username you want to use). You’ll be prompted to enter and retype your password, then the .htpasswd file will be created for you.

Creating the .htaccess file

Now that you have created and uploaded your password file, you need to tell Apache to use it to protect your page(s) or site. This is what your .htaccess file will do.

Open your text editor again, create a new file, and save it as .htaccess.

Protecting a folder

To password protect a folder on your site, you need to put the following code in your .htaccess file:


AuthUserFile /full/path/to/.htpasswd
AuthType Basic
AuthName "My Secret Folder"
Require valid-user

/full/path/to/.htpasswd should be the full path to the .htpasswd file that you uploaded earlier. The full path is the path to the file from the Web server’s volume root – for example, /home/username/.htpasswd or C:\wwwroot\username\.htpasswd. (If you’re not sure of the full path to your site or home directory, ask your Web hosting company for this info.)

The above .htaccess file will password protect all files in the folder that it is placed in, and all sub-folders under that folder too. So if you wanted to password protect your entire site, you would place the .htaccess file in your Web root folder.

Protecting a file

To password protect just a single file in a folder, use the following .htaccess file:


AuthUserFile /full/path/to/.htpasswd
AuthType Basic
AuthName "My Secret Page"

<Files "mypage.html">
  Require valid-user
</Files>

This will password protect just the mypage.html file in the folder where you put the .htaccess file.
500 GB of hosting for only $4.95/mo.

Uploading the .htaccess file

Once you’ve created your .htaccess file, upload it to your website, placing it in the folder (or folder containing the file) that you want to protect.

Testing it out

Now use your Web browser to visit the folder or file that you’ve protected. You should see a password dialog like the one shown at the start of this tutorial. Type in the username and (unencrypted) password that you chose earlier, and you should be given access to your folder or file!

(By the way: with this type of password protection, you continue to have access to the password protected stuff until you restart your browser.)

Problems?

If you can’t access your stuff and the dialog keeps popping up, check that you entered the username and password correctly. If it still doesn’t work, check the path to your .htpasswd file on the server – make sure the path specified in the AuthUserFile directive is correct. Also make sure that both the .htpasswd and .htaccess files are readable by the Web server user (chmod 644 should do the trick for UNIX/Linux/FreeBSD servers).

If the password protection isn’t working (i.e. you can still access your stuff without needing to enter a username/password), check that you uploaded your .htaccess file to the right folder. Also check that your web server supports .htaccess password protection (it needs to be an Apache server, and your server admin needs to have enabled the AuthConfig override for your site).

Password protecting more stuff

  • If you want to password protect other folders (that aren’t under the currently protected folder), simply copy your .htaccess file to the new folder to be protected.
  • To password protect more than one file in the same folder, just create more <Files></Files> blocks within the same .htaccess file – for example:

AuthUserFile /full/path/to/.htpasswd
AuthType Basic
AuthName "My Secret Page"

<Files "mypage.html">
  Require valid-user
</Files>

<Files "myotherpage.html">
  Require valid-user
</Files>

Adding more usernames and passwords

You’re not restricted to just one username/password. If you want to add other usernames and passwords, simply repeat the “Creating the password file” procedure above, but add each new username/password line to your existing .htpasswd file, e.g.:


fred:p29cmnwl4a0et
linda:vwp45xakfh89

Alternatively, if you’re using htpasswd to create your passwords, as described earlier, then you can add extra users with the command:


htpasswd .htpasswd linda

(where linda is the username you want to add). Make sure you don’t include the -c option when adding additional users, or htpasswd will attempt to create a new password file!

Further info

For full information on Apache’s mod_auth module (the module that does password protection, amongst other things), see the Apache mod_auth documentation.

Filed Under: Apache Tagged With: hide folder, private area, private folder, subscriber, subscription area

Reader Interactions

Comments

  1. im_abby says

    3 May 2010 at 12:31 pm

    Great article. I found it extremely helpful.

    However, I am struggling to figure out if it is at all possible using this method to password protect URLs that have dynamically been written from a database. These directories do not physically exist on the server, but I would like to lock out access to them.

    Is this possible using .htaccess?

    Reply
  2. cat says

    3 May 2010 at 8:10 pm

    Hi there,

    I think it should be possible. I do something similar with redirects for URLs that don’t physically exist on the server through .htaccess – I am doing my URL rewriting through .htaccess too though.

    Give it a try and see. I’d be interested to hear whether it works or not!

    Cat

    Reply
  3. looby says

    6 July 2010 at 10:51 am

    Thanks very much for this – it’s a lot clearer than some other “explanations”.

    I wondered if I could just mention something which will be obvious to most but with which I struggled. It took me a long time to work out what exactly to put in the AuthUserFile line. Eventually I realilsed that it must look something like this

    AuthUserFile /home/your_user_name/folder/.htpasswd

    I was originally trying

    /folder/.htpasswd

    which won’t work.

    Thanks again for a helpful article.

    Reply
  4. matt says

    7 July 2010 at 4:19 am

    @looby: Thanks for your contribution – I’m glad you found the article useful. 🙂

    Reply
  5. DaisyMae says

    24 September 2010 at 11:02 am

    Hi

    The password protection works like a dream, however once I’ve sumbitted the correct password I get an Internal Server Error.

    It’s the same error I get when I mess up the main website .htaccess file.

    The main website is still working ok.

    Do you have any ideas why it might be giving me this error?

    Thanks 🙂

    xxx

    Reply
  6. matt says

    26 September 2010 at 7:12 pm

    @DaisyMae: Take a look in your Apache error log – this will tell you the exact error message/problem.

    Reply
  7. skelkins says

    19 October 2010 at 4:21 pm

    This was a great tutorial: clear, easy to follow, and spectacularly useful. The very few times I’ve needed to do this, I’ve never remembered how it’s done, and it has always seemed to take me ages of searching around before I find a genuinely helpful how-to. This time, I’m bookmarking. Thank you so much for writing it!

    Reply
  8. matt says

    19 October 2010 at 8:21 pm

    Thanks @skelkins, I’m glad you found the tutorial helpful. 🙂

    Cheers,
    Matt

    Reply
  9. dougsix says

    21 November 2010 at 6:59 pm

    Your explanation was clear and worked fine for protecting web folders as described…..but
    I guess I was looking for something different.
    On my first web I have some sub-folders with pages in them.
    I want to prevent access dirctly into the sub-folders but allow the web browser to see the pages.
    Hope I explained that correctly.

    Thanks

    Reply
  10. matt says

    21 November 2010 at 11:02 pm

    Hi dougsix,

    If I understand you correctly, you want to prevent automatic directory listings. To do this with Apache, see:

    http://httpd.apache.org/docs/1.3/misc/FAQ.html#indexes

    Alternatively, you could put a blank index.html file in each directory.

    Hope that helps!

    Reply
  11. dougsix says

    22 November 2010 at 1:10 pm

    Thanks for the quick response.
    The blank index.html page seems to do exactly what I wanted. Now the contents of the folders ares not visible.

    Thanks again.

    Dougsix

    Reply
  12. matt says

    23 November 2010 at 11:37 pm

    @dougsix: Great stuff. You’ll find the .htaccess approach is generally more manageable, but the blank index.html technique works well if you only have a few directories to protect (and you don’t want to mess around with .htaccess files).

    Reply
  13. JustToSay says

    27 January 2011 at 9:36 am

    Thanks for the info on using htpasswd.exe that was welcome info. And the passwd protect works fine also. But I would like to add in my case here I had an error in the log every hit saying.
    client denied by server configuration: it was because I was allowing dir listing in the folder to fix that I added.

    IndexIgnore .htaccess to the .htaccess fixed the errors when it tried to read the dir listing every time.

    AuthUserFile c:webserverServerControl.htpasswd
    AuthName “WhoAreYou”
    AuthType Basic
    require valid-user
    IndexIgnore  .htaccess
    Options +Indexes
    # adding fancy directory indexing
    IndexOptions +FancyIndexing
    

    Thanks again for the nice how to..

    Reply
  14. matt says

    27 January 2011 at 10:36 pm

    @JustToSay: Thanks for the feedback, and the extra info. 🙂

    Reply
  15. tommie says

    8 February 2011 at 6:17 pm

    Love the explanation of how to protect folders and pages.

    I’m working on a script that will allow users in the system to “auto login” or ftp to a password protected folder from a link provided to them. Is this even possible and if not with .htaccess is there another way?

    ex:

    http://www.mydomain.com/protected-folder?username=USERNAME&password=PASSWORD

    [Edited by tommie on 08-Feb-11 18:48]

    Reply
  16. matt says

    9 February 2011 at 7:29 pm

    Hi tommie,

    You can specify a username and, optionally, a password in an ftp:// URL:

    http://www.cs.rutgers.edu/~watrous/user-pass-url.html

    Cheers,
    Matt

    Reply
  17. banafsajy says

    18 June 2011 at 6:26 pm

    hi, how do you get users to logout from the protected page once they are done viewing the content?

    Once I’ve successfully entered the protected page using this method and I close the window, the next time I visit the protected page it doesn’t ask me for a password anymore.

    So question is, how secure is this?

    Reply
  18. matt says

    23 June 2011 at 3:37 am

    @banafsajy: You can’t really. The browser stores the credentials until it’s closed:

    http://en.wikipedia.org/wiki/Basic_access_authentication#Disadvantages

    If you need to support timeouts and logouts then the best bet is to use server-side code (PHP, ASP etc) with sessions. This also gives you more security since the credentials aren’t sent by the browser with every request – only the session ID is sent.

    Cheers,
    Matt

    Reply
  19. gordon says

    29 February 2012 at 2:55 am

    I tried this.
    I put the password above the root directory.
    Everything works well, except that if instead of entering a username and password, I just hit cancel, it takes me right into the directory I was trying to protect.

    Any suggestions?

    Reply
  20. matt says

    4 March 2012 at 11:43 pm

    @ gordon: No idea without seeing your .htaccess and password files. Sounds like maybe your Apache isn’t set up for HTTP auth properly.

    Reply
  21. derek7467 says

    27 November 2012 at 12:45 pm

    Can i specify an error page if the user hits cancel and gives bad credentials?

    Reply
  22. derek7467 says

    27 November 2012 at 1:12 pm

    figured it out. thanks.

    Reply
  23. starpnc says

    17 November 2013 at 5:20 pm

    Question for you. I used htaccess to password protect a page of my website previously. I want to password protect a new page of my website, but make a new password for this page that will not work on the other page. My old computer died, and I got a new computer. I have been trying to find the htaccess and htpasswd files with no success.

    If I want to password protect this new page with different passwords, am I out of luck? Is my only option to put it in the same folder with the already password-protected page, and use the same password as it? Any suggestions on what I should do?

    Reply
  24. chrishirst says

    17 November 2013 at 6:17 pm

    Put it in a different directory with it’s own .htaccess file and .htpasswd file

    Bearing in mind of course that a .htaccess file applies to all subdirectories off the directory as well.

    Reply
  25. starpnc says

    18 November 2013 at 10:13 am

    I tried doing that, it doesn’t seem to work! At best I can only get the other page to be password protected. This one shows no matter what, even if I put it in the same folder and add more <Files></Files> blocks. Any suggestions would be greatly appreciated!

    Reply
  26. chrishirst says

    19 November 2013 at 4:46 pm

    Do you have a .htaccess file in the document root directory?

    If so, the directives in that will cascade along the entire directory tree and take precedence over ‘local’ .htaccess directives.

    Reply
  27. starpnc says

    19 November 2013 at 10:41 pm

    Hi Chris, it’s in the main folder of my website. I have some IP addresses blocked in the htaccess file as well. The file that’s password protected is in a folder called “Private_folder”.

    I also specified:
    AuthUserFile /home/content/s/h/i/shinycrayons/html/.htpasswd
    AuthType Basic
    AuthName “Resume”

    <Files “cv.html”>
    Require user shinycrayons
    </Files>

    If I want to password protect another page in the same folder, what would I enter?

    I’m new to this, so thanks for your help in advance!

    Reply
  28. chrishirst says

    20 November 2013 at 9:50 am

    To protect multiple files you need to use a FilesMatch directive with a regular expression OR (|) and put the match patterns in paranthesis.

    The IfModule directive is not required, it is simply a check that Apache has been compiled with mod_auth included

    <IfModule mod_auth.c>
          <FilesMatch "(filename.ext)|(filename2.ext)">
               AuthName "Username and password required"
              AuthUserFile /home/path/.htpasswd
              Require [valid-user-name]
              AuthType Basic
        </FilesMatch>
    </IfModule>
    

    If you want different usernames and passwords for different filenames you add name:password pairs in .htpasswd

    user1:r992@L24y8
    user2:23849&h74U
    

    and use Files or FilesMatch directives for each file name

    The thing to be wary of is going over the top with htaccess directives, simply because it is loaded and read on every request to the server. So a few dozen lines of directives can add a significant extra load to a fairly busy server.

    [Edited by chrishirst on 20-Nov-13 09:53]

    Reply
  29. starpnc says

    20 January 2014 at 7:16 pm

    Thanks, Chris. I figured out what the issue was after many tries. The FilesMatch directive was fine. But the quotes I had were incorrect: they weren’t straight double quotes, which threw everything off. I got it to work! Thanks for all your help.

    Reply
  30. Ruedi_web says

    12 May 2014 at 9:21 am

    The password protection works well, but with .htaccess I get problems with Apple TV ( Airplay). Videos can not be streamed with an active .htaccess file. Without .htaccess Airplay works with the same video-files.
    What can I do?

    Reply
  31. rohanwij says

    12 May 2014 at 9:48 am

    Great article, clear and helpful – thanks Chris.
    I got it working without any problems (to restrict access to some short videos).
    My query is: Is there any way to change the default wording that is displayed in the authentication window.
    “A username and password are being requested by http://www.website.co.uk. The site says: ‘EnterPassword’ .” I know you can change the “EnterPassword” with new text in AuthName but the sentence ‘The site says…’ is superfluous. Actually a simple ‘Please enter Username and Password’ is all that’s required and would look much better. Can this be done?
    If anyone knows, I’d appreciate it. Thanks in advance.

    Reply
  32. rohanwij says

    12 May 2014 at 9:52 am

    btw the above website.co.uk is not mine, just used ‘website’ as a generic term.

    Reply
  33. seriousssam says

    4 January 2015 at 9:21 am

    Just created an account to say thank you 🙂 super useful. Found this post helpful when it didn’t work the first time (using Ubuntu server): http://www.linuxquestions.org/questions/linux-server-73/htaccess-and-htpasswd-not-working-865318/.

    Reply
  34. Ajayghosh TS says

    6 March 2020 at 7:03 pm

    The article is good and easy to understand. I have tried to protect a web page exactly as suggested by you. But it failed; the protected page is directly displayed without any pop-up window for username/password entry. What will be the possible reason? See below the code for .htaccess file:

    AuthName "Please enter User & PW"
    AuthType Basic
    AuthUserFile /.htpasswd
    <Files "programs.html">
    Require valid-user
    </Files>
    

    Please help.
    Thanks

    Reply
    • DIeter says

      4 December 2022 at 12:01 pm

      I know that my reply is very late, and unfortunately I cannot provide a solution.

      I also have the same issue. A syntactically correct vhost-declaration in Apache2.4.54 gives access to any user without displaying the login box. All AUTH modules are enabled. But this does not help.

      Walking through all the tutorials on “Basic Auth” I could not find an explanation for Apache’s wrong(?) behaviour. It could be a bug, or it could be a feature.

      Apache2 should be security-aware, but obviously it s not.

      Furthermore I wonder why most “experts” base their ideas and tutorials upon a .htaccess file. According to Apache2 documentation the contents of a .htaccess file is read and evaluated EVERY TIME the corresponding document root is to be accessed.

      As a consequence, deploying .htaccess files is useful in the creation phase of a web-site but not in production. Instead incorporate the .htaccess directives into the vhost files. These directives will be “compiled” when the Apache2 server will be restarted (systemctl restart apache2).

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits