header-menu

Thursday, May 23, 2013

How to Password Protect a page with .htaccess

There are times when we want a page to be visible to only authorized users but we do not want to write a backend code to do it. With the Apache server, such limited access can be enabled by writing certain code in the file named .htaccess and storing user information in .htpasswd file.

Lets see how to do it, step by step:

1 - First create a new file in any text editor and write the following code in it.


  1. AuthUserFile path/.htpasswd
  2. AuthType Basic
  3. AuthName "Name of Auth"
  4. <Files "file-to-protect.php">
  5.   Require valid-user
  6. </Files>

Lets understand the above code.


  • In the first line, 'path' refers to the absolute path to the folder in which your .htpasswd file will be saved. This is the path from the root of your server, to your folder. 
  • In the third line 'Name of Auth' is just a name you give to your authentication. You can choose your name here.
  • In the fourth line, 'file-to-protect.php' is the name of the file that you want to protect. In this case, I am supposing the the htaccess file is in the same folder as the file to protect. 
2- Save this file as .htaccess. While saving your software may give you a warning, but just do it. 

3- Make another new file in your text editor and write the following code in it:


  1. username:password
4- In the above code, you should have the password in encrypted for. You can get an encrypted password from a link like this :  http://www.4webhelp.net/us/password.php

5- Save this new file by the name of .htpasswd

6- upload both these files to your desired folder and try it out. Now when the page opened, it will ask for authentication.






No comments:

Post a Comment