December 4, 2010

use .htaccess to protect your web folder

Generate the password file

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.

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.)

Creating the .htaccess file

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.

No comments:

Post a Comment