How to add HTTP Authentication to a Drupal development site using .htaccess and .htpasswd

| | 3 min read

Password-protecting drupal development site with .htaccess file

There might be few scenarios when we need to protect our site from the general public and make it accessible to a selected group of users. One of the most common scenarios in the development workflow of a Drupal site is when you want to avoid your half-complete drupal site showing up in Google search results.For such needs, it is advisable to go for password-protecting the site using HTTP authentication.

If you have cPanel installed on your hosting server, you can use the ‘Password Protect Directories’ option from the ‘Security’ section on the cPanel home page. Click here to read on How to enable HTTP Authentication using cPanel (link to an article for the same on our site)
For those without cPanel, here’s how to get Apache work your way:

Password protection on directories using .htaccess and .htpasswd:
On a hosting server running using apache as the webserver, you need to do the following things to add HTTP Authentication (password protection) to your site:

  1. Create .htpasswd file
  2. Add/modify .htaccess file

1. Create .htpasswd file
.htpasswd (do not forget to add the ‘.’ before htpasswd) is the file that stores the HTTP username and password. You need to tell Apache to verify against the credentials given in .htpasswd.

First, to create .htpasswd with the desired username and password, SSH into your server (or open up a terminal window on your local machine, cd (change directory) to the folder where you want to create your password file, and type in the following command:

htpasswd -c .htpasswd 

You'll be prompted to enter and retype your password, then the .htpasswd file will be created for you.
Here’s what it looks like:

user@user-desktop:~$ htpasswd -c .htpasswd userjohn
New password:
Re-type new password:
Adding password for user userjohn

If you open up the file, you can see the username and encrypted password generated. It looks something like this:


Step2: Add/modify .htaccess file
.htaccess (that too, with the ‘.’), is the file that tells apache what custom settings to use for the site. What we have to do here is that we have to add the setting in .htaccess that tells apache to use the password in .htpasswd. Drupal has a default .htaccess file in its root. You just have to put in the following lines of code to your .htaccess file:

AuthUserFile  //.htpasswd
AuthType Basic
AuthName "Restricted Access"
Require user userjohn

is the path to the file from the Web server's root folder - for example, /home/username/.htpasswd or C:\wwwroot\username\.htpasswd.

The above .htaccess file will password protect all files in the folder that it is placed in, and all sub-folders under that folder. For protecting your entire site, just place it in your web root.