Password Protect your webpages using htaccess

Recently a serious security flaw was discovered on one of my webpage where a folder which was intended to be accessed just by admin was open for access to anyone. I somehow ignored that folder as it was lying there for years. Fortunately before those sensitive information could compromised, one of the site follower sent me an email describing the serious flaw in security. I acted promptly and secured those folders with passwords. It is always a good idea to add password protection to any of the folders / webpages of your website if you want restricted access on them. Here I will describe an easiest way to add password protection to your webpages.

1. Easy and Automated Way

First, let us see the easy way of adding password protection to a webpage. In the CPanel of your sites hosting server you can configure folders and add passwords to those folders/pages. Login to your CPanel and scroll down to see the Security box Select Password Protect Directories under Security. It will open up a page where all the folders will be listed. Click on any of the folder name where you want to add password protection. If you want to add password to a subfolder like /myweb/mysecretfolder/ than click on the folder icon and it will list all the subfolders under it. Once you select a folder, it will ask for username / password and foldername. Check the following snapshot. Select the checkbox “Password protect this directory” and also provide a name for protected directory. The directory name that you provide here will be used in the password prompt dialog box when user tries to access this folder. And that’s it. All you have to do is to try accessing the secure folder from internet. As soon as the secure folder is requested, user will be asked to enter username/password. If user is successfully authenticated the content will be served. Otherwise an Unauthorized error (401) is generated. The above method that we used to protect any webpage using CPanel’s Password Protect Directories option uses Apache’s Basic authentication mechanism. Behind the scene it generates 2 files, first one a password file which stores the username/encrypted password pairs for all authorized users and second file is .htaccess file which contains the rule for authentication, the path to the password file and other details.

2. Manual Way

As mentioned earlier the above (Easy and Automated) method generates the password file and rules in the htaccess file which set the authentication mechanism on the folder. Let us see the manual way of doing this. The advantage is that things are clear and you know exactly what is going on in the background. You also get some additional functionality such as password protecting single or multiple files. There are two things we need to do here.
  1. Generate the password file
  2. Add authentication rules in htaccess file

1. Generate the password file

All the username/passwords that we need to give access to the folder goes in a file. The format of this file is simple, you have : pairs on each line for each user. For example:
john:#343Jjdsk&^#nsnsdj jil:$%24334nke43$*#@4m
Code language: HTML, XML (xml)
The trick here is to generate the encrypted passwords for this file. Fortunately we lot of online tools that can be used to generate these encrypted values. Use any of the below tools to generate your encrypted passwords. Save the username/password in file .htpasswd. We need to protect this file so keep it anywhere but not in public_html or web root. Most of the hosting providers a folder .htpasswds under your user home directory. Store the file .htpasswd in .htpasswds folder. If you dont have this folder then you can store the file anywhere. The apache mostly restricts the direct access to files starting with .ht. So feel free to put the file at location of your choice. For this example lets assume the location of password file is: /home/username/.htpasswds/.htpasswd

2. Add authentication rules in htaccess file

Now as we have created the password file, let us add the htaccess rules for authentication the htaccess file. Open the .htaccess file inside the folder that you want to protect with password. Create one if not already exists. Copy following code into it.
AuthName "My Secret Folder" AuthType Basic AuthUserFile /home/username/.htpasswds/.htpasswd Require valid-user
Code language: HTML, XML (xml)
Change the AuthName to anything you like to be shown in password dialog box when this folder is accessed. Also change the AuthUserFile to the full path of password file that we created in step 1. And that’s it. Try to access the folder from internet and apache will prompt you for username/password. If successfully authenticated, user will be served with appropriate content.

Protecting a single file

To password protect just a single file in a folder, use the following .htaccess file:
AuthUserFile /home/username/.htpasswds/.htpasswd AuthType Basic AuthName "My Secret Page" <Files "mypage.html"> Require valid-user </Files>
Code language: HTML, XML (xml)
This will password protect just the mypage.html file in the folder where you put the .htaccess file.

Protecting multiple files

To password protect more than one file in the same folder, just create more blocks within the same .htaccess file – for example:
AuthUserFile /home/username/.htpasswds/.htpasswd AuthType Basic AuthName "My Secret Page" <Files "mypage.html"> Require valid-user </Files> <Files "mysecondpage.html"> Require valid-user </Files>
Code language: HTML, XML (xml)

Disabling password protection for localhost

You may have setup a website in production and a development environment on your localhost. While it is desirable to have password protection for production version, but at same time it is very annoying if on localhost (dev environment) it keeps on asking for password everytime. Add following rule in your .htaccess file and the server will never ask for password if you are running the website on localhost.
Require valid-user Allow from 127.0.0.1 Satisfy Any
Code language: HTML, XML (xml)
For more info: http://httpd.apache.org/docs/2.0/mod/core.html#satisfy

Disabling password protection for subfolder

It may happen that sometime we have a requirement where to add password protection to a folder but not for a particuler subfolder. – /mysecret/* should be protected by password – /mysecret/mypublic/* should be open to all This can be achieved by creating a new .htaccess file in subfolder (mypublic) and add following line into it.
Satisfy Any
Code language: HTML, XML (xml)
I hope things are clear from above tutorial. If you think you have a better way of doing this, share your experiences :)

View Comments

  • Nice tutorial guys... can you provide me any tutorial to create our own .htaccess file for chaning the extension of file like example,html to example.php or even
    "example.com/username"
    I`m searching that article daily but cant find!!!!!!!!!!!!!!!!!!

    • Hi Mitran, to change your extensions from one from to another you have to add the rules in the .htaccess files. I mean you have to know the regular expression syntax. If you know better regular expressions then you can change you extensions to search engine friendly forms..

  • I had been searching for this type of password protection from a long time.
    Very nice and informative article.

  • What if I want to give different access to different users. For example,
    For Page 1: I want A, B to access it.
    For Page 2: I want A, C, D to access it
    For Page 3: I want B, E to access it.

    How can I add such specifications for the different pages in my .htaccess file.

    Thank You

    • in this case use group authorization, add users to groups and use .htgroup file
      or specify users for each page ... both is acceptable

      here is the example with users for each page

      AuthUserFile /home/username/.htpasswds/.htpasswd
      AuthType Basic
      AuthName "My Secret Page"

      Require user usr_A usr_B

      Require user usr_A usr_C usr_D

      Require user usr_B usr_E

  • I need to protect a forum that may be accessed by members of the same household. Browers usually cache the user name and password, so that the password info is not required on subsequent visits.

    Is it possible to create a time-out function, so that users are automatically logged out? I see this on financial management websites, where login info is required with each visit.

    Thanks very much.

  • Nice tutorial. but i did everything as told but my site is still not secured...i am in fix... :(( please help........

Share
Published by
Viral Patel
Tags: apache htaccess PHP security

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

5 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

5 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

5 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

5 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

5 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago