Protect Folder With Htpasswd In Apache


Need a folder secured on your website with a username and password prompt? You may have some important documents you need to share with selected people. You could have restricted downloads you need to give to certain people. In any of these cases, you can secure a folder with one or multiple usernames and passwords.

Secure Folder With Htpasswd

Secure Folder With Htpasswd

I will show you how to lock down a folder using apache .htpasswd and .htaccess. Once a folder is password protected with htpasswd and htaccess, your website visitors will see a dialog box appear similar to the one below and they will need to enter a username and password before they can access the contents or downloads of that locked folder.

Protect Folder With Htpasswd In Apache

Below is showing what the end result will look like and what this article will help you achieve.

Step 1 – Create the folder and set the permissions on it

If the folder you want secured doesn’t exist, go ahead and create it. Then set the correct permissions and owner for the folder. I am using www-data as our folder owner as this is the owner that apache website runs as.

cd /var/www/html
mkdir secured_folder
chmod 744 secured_folder
chown www-data.www-data secured_folder
cd secured_folder

Step 2 – Create your .htaccess file

Change to the ‘secured_folder’ and create an .htaccess file inside their with the contents below. This will add the username and password security to the folder.

AuthUserFile /var/www/.htpasswd
AuthGroupFile /dev/null
AuthName "My protected files"
AuthType Basic

<Limit GET>
require valid-user

Step 3 – Create the username and password for .htpasswd file

Now change to the folder you want your .htpasswd is to be stored in. We specified /var/www/.htpasswd as you can see the above for ‘AuthUserFile’. Then use the htpasswd function in your command line to create the username and password for the folder you want to secure. It is recommended that you leave this file outside of the actual website folder.

cd /var/www/
htpasswd -c .htpasswd username1

You will be asked to enter a password for ‘username1′.

Step 4 – Adding more users to .htpasswd file (optional)

If you would like to add multiple users to the same .htpasswd file then don’t add the ‘-c’ option.

cd /var/www
htpasswd .htpasswd username2
	you will be asked to enter a password for 'username2'
htpasswd .htpasswd username3
	you will be asked to enter a password for 'username3'

Now when you go to visit your page, it will prompt you to enter a username and password before you can access the page.