How to Protect Your Website Using .htaccess

If you want to protect your website so that it can only be accessed by someone who has a username and password, you can do so by using .htaccess. The following is just an example of one way to do this.

Step One: Make an .htpasswd File

Start by opening up a plain text editor and adding a line that contains your username and password, separated by a colon. The password will need to be encrypted in a special format that can be used for htaccess password protection. On Linux you can use the htpasswd tool from apache2-utils to do that. And there are many online tools to help do so, such as this.

The contents of your .htpasswd will look something like the following, using your own username and password:

ryan:oeteHNuwJnH7k

Then, save your file as .htpasswd and upload it (using ASCII and not BINARY) to your web hosting in the directory under vhosts/ corresponding to your site, like this:

/srv/data/web/vhosts/www.mysite.com/.htpasswd

Warning

Do not put this in your htdocs folder.

Step Two: Make an .htaccess File

Also in a plain text editor, add some content like the following:

AuthUserFile /srv/data/web/vhosts/yourvirtalhostname/.htpasswd
AuthName "Password Protected Area"
AuthType Basic

<limit GET POST>
require valid-user
</limit>

Be sure to edit the AuthUserFile line to correspond to the absolute path of your .htpasswd file.

You can personalize the password prompt by changing what comes after AuthName.

You can then upload this file to directory you want the contents of the file to affect. The .htaccess file will be enforced on the directory it is located in, as well as all sub-directories.

For example, you can place it in the root of your virtualhost to protect the entire site:

/srv/data/web/vhosts/www.mysite.com/htdocs

Or, in a particular directory to protect it:

/srv/data/web/vhosts/www.mysite.com/htdocs/myprivatestuff/