There are many reasons why you would want to password protect your website, or a section of your website. For example, your website could be under development and should only be accessible by yourself or your clients. Or you may want to limit access to an admin area or a photo gallery.
If your website is served via the Apache web server, password protecting specific areas can be implemented quite easily using a
.htaccess file. The process consists of two parts. The first step is to generate a password file. The second step is to implement the rules and reference the file.
To create the password file you should use the
htpasswd command line tool. This is usually installed as part of the Apache web server. SSH in to your server and run the following command:
htpasswd -c .htpasswd <username>
<username> is the name you want to use in the ‘User name’ section of the login prompt. When you hit enter it will prompt you for a password, and then ask you to confirm it. Note that you won’t see anything on the screen when you enter your password.
> htpasswd -c .htpasswd Andrew New password: Re-type new password: Adding password for user Andrew
When this is done your password will be encrypted in the
.htpasswd file. To see this, use the
> cat .htpasswd Andrew:$apr1$ljvK4NbA$ww9drMuLx3FKwXu0ofkZh1
For security reasons you MUST keep this file OUTSIDE of your website public directory. A good place to put this is one directory above your web directory. E.g, if your website is served from
/home/username/public, your password file would live at
Now that you’ve created the password file you can set up the htaccess file to handle the password protection. Inside your website public directory, either create or edit the
.htaccess file and add the following:
AuthName "Password Protected Website" AuthType Basic AuthUserFile /home/username/.htpasswd Require valid-user
.htaccessfile inside the directory and add the code above.
Based in Staffordshire, UK