How to set up .htaccess to password protect a website or directory.
This brief guide is for those of you running an Apache web server in a windows environment. This is an easy to follow guide for basic password protection of a directory on your Apache powered server. This is in no way a complete guide – but should get your website directories protected quickly.
There are two files that you need to create for this to work.
Create the password file.
First off let’s make the password file. If you’re running your own Apache server (either standalone or installed as part or xampp or similar) then you have the tool to do this already. The file we need to use is called htpasswd.exe
On our Apache server the file we need is located here;
C:/Program Files/Apache Software Foundation/Apache 2.2/bin/htpasswd.exe
If you’re using xampp then it could be located somewhere like this;
This is a command line only tool so open up a command prompt, and navigate to the folder that contains the htpasswd.exe file. To get to the root of your C: drive use a cd.. or two to get up a level.
C:\Users\admin> cd.. C:\Users> cd.. C:\> cd program files\Apache Software Foundation\Apache 2.2\bin
next call the command to create your password file using the line below.
C:\> htpasswd.exe -c -b .htpasswd username password
Replace username and password with whatever you want users to have to type in to access your protected directory.
This will create your .htpasswd file. You can either leave the file where it is (in the same directory as the htpasswd.exe command) or move it elsewhere. Just remember it’s more secure to place it somewhere above the root of your web directory.
Now create the .htaccess file.
Next up let’s make the .htaccess file. This is the file we’ll drop into the directory we want to password protect. This will then prompt for the username and password. Open up a text editor like notepad and copy the following lines into it.
AuthName "Protected Area" AuthType Basic AuthUserFile C:/Path/to/file/.htpasswd require valid-user
The AuthUserFile directive should be the path to wherever you put the .htpasswd file you created earlier. If there are spaces in any of the folder names then enclose the path in quotes like this.
AuthUserFile "C:/Program Files/ Apache Software Foundation / Apache 2.2/Bin/.htpasswd"
Save the file, remember it needs to be called just .htaccess nothing more. Place the file in the folder you want to protect. Then visit the folder in your browser and you’ll be prompted for the username and password you set up earlier.