How to Password Protect a Directory on Web Server

The main reason to protect a directory on a web server, is to restrict access. Usually, this is done in a directory with private content. The easiest way to restric access to a directory on a web server, is using htaccess password protection.


This method provides a username and password authentication to the directory, files, and sub-directories. The .htaccess file is a hidden file, which is placed in the same directory you wish to protect. This file works in conjunction with .htpasswd file, which contains a database or mapping of username:password. When the user access any content inside that directory, the Web Server reads the directives inside the .htaccess file, and prompt the user for authentication.

Let’s say you have a directory on your site you wish to protect. The name of the directory is “data” and its full path is /home/username/d/a/data/
1- Create an .htaccess file. The .htaccess file contain this basic directives.

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /home/username/d/a/data/.htpasswd
Require valid-user

There are two directives you have to edit, one is the “AuthUserFile” directive. This directive contains the full path to the .htpasswd file. And this file should be in the same place as .htaccess file. In other words, both .htaccess, and .htpasswd should be place a the root of the directory you want to restrict access.
2-Find the full path to your .htpasswd file. You can do this in two ways.
Open your terminal, and change directory into intended directory. Then run ‘pwd’ command. This will print out the full path to that directory.(Linux only)

-bash-3.2$ cd html/private/
-bash-3.2$ pwd

The second method is to use the following snippet of code, and place it in a file called fullpath.php. create a file called fullpath.php. Then, place the file inside the directory.

$dir = dirname(__FILE__);
echo "<p>Full path to this dir: " . $dir . "</p>";
echo "<p>Full path to a .htpasswd file in this dir: " . $dir . "/.htpasswd" . "</p>";

Next go to your browser and execute the file
3-Use the result and enter it next to the AuthUserFile directive in .htaccess file.
4-Generate user:password combination for .htpasswd file. Use the following link to generate a password hash for your username. Then enter the output in your .htpasswd file. The file should contain one user:password combination per line.


5-Place both files inside the protected directory. Next, create an html file: index.html and insert the following code.

<h1>Hello World</h1>

6-Save the file and place it inside your directory.
7-Browse to the index.html file ie: and you should be prompted for username and password. If everything was configured correctly, you should have the index.html page displaying “Hello World” in your browser.

Share This!

Leave a Reply

Your email address will not be published.