Oct 032012
Article Apache

In the apache web server, as happens in other web servers, it is possible to restrict access to a given directory. If a user tries to access a page inside this directory, the server will request a valid username and password to proceed. This post explains how to configure the web server to implement this functionality.

To do this, we must create in our server a file named “.htpasswd” (where the first character is a period) in a directory that is not accesible using an url  (In this example, we will create the file  “/path/to/.htpasswd”). This file will contain the usernames allowed access and their passwords.


Defining users in .htpasswd

The .htpasswd file can be created and maintained using the ‘htpasswd’ command included in the apache installation.

Example: create a .htpaswd file with a user named ‘john’:

As we see, the new .htpasswd file just created is a text file with a single line in it, having the unsername and the encrypted password separated by the “:” character.

Creating a .htaccess file

Next, we create a file named “.htaccess” under the directory we want to protect, with the following contents:

We can also avoid the creation of the .htaccess file by placing the AuthUserFile directive directly in the apache configuration file:

Testing the configuration

Once both .htpasswd and .htaccess  files have been created, when a browser tries to access the url of a file under the directory where the .htaccess file has been placed, the server will request the username and password to validate the access:



For this procedure to work as expected, the directory being protected must be granted the “AuthConfig” permission. This permission is granted by means of an “AllowOverride” directive in the apache configuration file (typically, this configuration file is located in /etc/apache2/httpd.conf).

Inside the configuration file, the AuthConfig permission is granted by adding the directives:

 Posted by at 7:13 pm

  One Response to “How to protect a web page with username/password in apache”

 Leave a Reply