Many times when we do not want the public to access a particular folder, we can block it by setting up Password Protection using the .htaccess file. This article shows how to setup password protection.

The most common use case is when you are setting up a new website and you have copied the new files to a folder under your existing website. However, the current website being public will easily allow users to access the sub folder under your current Document Root. Hence, to prevent public access to this sub-folder, we can setup password protection using .htaccess and htpasswd.

Steps to setup Password Protection

Step 1: SSH into the server.

bash> ssh -l <user name>  <Your server IP Address>

Step 2: Move to the folder where you need to set up password protection. In most cases, the document root will be in the following location – /home/<user name>/public_html/

bash> cd /home/<username>/public_html/new_folder

Step 3: Use the following command to create a .htpasswd file with username and password to login inside the new_folder.

bash> htpasswd -c .htpasswd User1

Step 4 : Ensure the .htpasswd file is set to permission 644

bash> chmod 644 .htpasswd

Step 5: Now lets create a file with the following name .htaccess

bash> touch .htaccess

Step 6: Open the file and insert the following content into the file. So that it protects the folder and request login credential to access the contents inside new_folder

bash> vi .htaccess

After opening the file using VI editor, insert the following content into the .htaccess file

#Password Protection Test

AuthName “Dialog Prompt”

AuthType Basic

AuthUserFile /home/username/public_html/new_folder

Require valid-user

Step 7: Now try accessing the new_folder and it will give you a dialog box to enter user name and password. So only users with valid login will be able to access contents inside the new_folder. 

Hope the above steps helped you on how to setup password protection using .htaccess.

How to setup password protection

Meanwhile, if you want to password protect using a script, then here is one that I have created.


echo “Script to protect your folder”

echo “Path to the folder which needs to be protected”

read p_path

cd $p_path

echo “Enter User Name”

read username

echo “Enter Password”

read password

htpasswd -b -c $p_path/.htpasswd $username $password

if [ “$?” == “0” ];


echo ” Sucess – htpasswd file is created”


echo ” Sorry, something went wrong”


cd $p_path/

chmod 644 $p_path/.htpasswd

touch .htaccess

echo ‘AuthName “Dialog prompt”

AuthType Basic

AuthUserFile ‘$p_path’/.htpasswd

Require valid-user’ >> .htaccess

echo “Thank you for using the script”

By Liz Mathew

Founder, InsightDials

error: Content is protected !!