Password-Protecting your pages with .htaccess

If you develop websites or adminster them, you’ve probably been asked or required to password-protect parts of a website. 

So, to help you out, here’s a quick how-to in Apache using .htaccess:

  1. Open a terminal window and navigate to the folder or page(s) you’d like to add a password requirement.
  2. Once there, type the following: htpasswd -c .htpasswd username.  BTW, you can name .htpasswd to another name (something that is hard to guess is preferable).
  3. Enter the password you’d like to associate with the username (from above).  This will create the user and an encrypted password.
  4. Next, create the .htaccess file by typing: vi .htaccess, and add the following in the .htaccess file:

To protect a folder

AuthUserFile /full/path/to/.htpasswd
AuthType Basic
AuthName “Your Secret Folder”
Require valid-user

To protect a page

AuthUserFile /full/path/to/.htpasswd
AuthType Basic
AuthName “Your Secret Page”
<Files “yourpage.html”>
  Require valid-user
</Files>

Note: You can use a different name for .htpasswd so it’s harder for a hacker to figure it out.

5.   Type :wq! to save and exit. 

6.   For better security, perform a chmod on .htaccess, like so: chmod 644 .htaccess.

As you can see, the steps above are pretty straight-forward.  Also as an FYI, Apache blocks any requests for anything that start with “.ht”.

That’s basically it, I hope this post helps you out.  =0)

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.