Wednesday, August 21, 2013

Basic Authentication with .htpasswd in Xampp (Windows)

The basic http authentication created with .htaccess and .htpasswd files works pretty well on online real server. However implementing them locally on our Xampp server (on Windows) may be a little problematic. Here I am going to discuss the steps required to achieve this.

First of all, we need 2 files need to be created, .htaccess and .htpasswd. All the user passwords are stored inside the .htpasswd file. Windows does not allow to create such nameless files, however we can create them with Command Prompt. Check the picture below.



We have used the DOS command "copy con <filename>". Pressing CTRL + Z would end the process and creates a new file with the name provided. This way, we created the required .htaccess file. Our working folder is "htpassword". We created the .htaccess inside that only.

Next we would create the .htpasswd file with the help of command 'htpasswd', the corresponding windows executable file 'htpasswd.exe' resides in xampp\apache\bin folder. So, check the next screenshot to understand how we create the password file required for authentication.



We gave the command "htpasswd -c -m -b .htpasswd admin admin_pass". "admin" is going to be the username and "admin_pass" would be our password.

-c : create a new file
-m : MD5 encryption is enforced
-b : Use the password given at the command prompt

So, our .htpasswd file is successfully created. Our working folder "htpassword" also has an index.php file which contains a one-liner welcome message.

Now, open the .htaccess file, we need to write the following lines inside it.

AuthName "My Protected Area"
AuthType Basic
AuthUserFile c:\xampp\htdocs\htpassword\.htpasswd
require valid-user


Check the third line where the path of the password file is clearly mentioned. Now when we try to go to http://localhost/htpassword, a prompt appears asking for user id and password ( this is shown in screenshot below ). If valid id and password given, then we are redirected to index.php or other file set to be the default file.
 


3 comments:

Unknown said...

Thanks for your clear and useful post. It saves my day!
I just have one more comment about creating .htaccess file, you way didn't work on my PC so i tried with another command "notepad .htaccess".
Thanks again,
Max

Anonymous said...

Works like magic, thanks a lot!

Panayiotis said...

That is a great post. I followed the instructions and worked great!!!