Create a .htpasswd file in your Apache WebServer
For this you first need to create a file called .htpasswd where you will be storing all your authorized usernames and respective passwords.
Format – username:password_encrypted_for_htpasswd_file
This denotes the username is admin and password is 123admin (
53PWde6fcsrdois encrypted form of 123admin).
Easily Generate .htpasswd Encrypted PasswordsHere is an excellent password generation tool from Dynamic Drive to generate .htpasswd excrypted username and passwords.
Now you need to save the .htpasswd file in some directory other than your document root i.e. public_html. This is because your .htpasswd file should not be browsable with any url, otherwise everyone will be able to get your usernames and passwords.
Let’s put it here -
Password Protect a Web Directory and Sub Directories with .htaccessNow go to the web directory which you want to password protect. Create a .htaccess file if it not already there.
And add the following script –
AuthName "Restricted Area"AuthName – Title of the pop-up message box which will appear for validating username and password.
AuthType – Basic mean this is a HTTP authentication.
AuthUserFile – path to the .htpasswd file. Remember this path is the full server path and not a url related to your site.
Require valid-user – This means all the users mentioned in your respective .htpasswd file are allowed to access that directory.
If you want specific user to be able to access the directory then you mention –
Require user admin– which means only the user admin will be able to access the web directory.
Now this .htaccess provides password protection to the whole directory and all sub directories it is within.
Password Protect an Individual WebPage or Particular URLs with .htaccessIf you wish to restrict your users to some specific webpages or urls the use this script in the .htaccess file.
AuthName "Restricted Area"In this way you can control user access for each single file on your server with the help of .htaccess and .htpasswd. Now password protect your website and web pages securely with this simple tutorial script and be safe.