Extra security for user login & admin areas

July 25, 2018

Some Drupal sites don’t allow regular users to log in at all; they may only be used by administrators. In such cases it may be desirable to lock down access to the login and admin screens. This can be done using htaccess.

In this example let’s assume the site is installed at /var/www/yoursite.com/public_html. First you need to create the .htpasswd file. You should not put it in public_html – it needs to be outside your web root. In this example we can put it at /var/www/yoursite/.htpasswd which keeps it in a logical, easy to find place. To create this file do the following:

  1. htpasswd -c /var/www/yoursite.com/.htpasswd yourdesiredusernamehere
  2. Next it will ask you to enter a password (hit enter afterwards). Then it asks again.
  3. Done

In your web root folder (where Drupal is installed) open up .htaccess. If you’re using the command line, type:

ls -lah

That will show all files, including normally hidden “dot” files.

Go into public_html and edit the file (e.g. “nano .htaccess” or “vi .htaccess”) and add the following code to the top or bottom of the file;

AuthUserFile /var/www/yoursite/.htpasswd
AuthType Basic
AuthName "Sorry"
Require valid-user

Now http://www.yoursite.com/user and http://www.yoursite.com/admin are protecting the Drupal login form from brute force attacks. Doesn’t mean it still couldn’t happen, but it makes it much less attractive to the brute force attackers. This approach is not a good for sites that need to allow regular users to log in. This is intended only for sites with NO regular users who need to log in to the site. Admin users can still get in. You can set it up so each admin user has his/her own unique htpasswd username/password, or they can all share one. In any case their Drupal logins will differ.