Protecting your website by .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 1: make a .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 (this is an EXAMPLE; yours will have your own username and password):

ryan:oeteHNuwJnH7k

Then, save your file as .htpasswd and upload it (using ASCII and not BINARY) to your instance in the directory under vhosts/ corresponding to your site (don't put it in the htdocs/ folder!), like this:

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

Step 2: make a .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 (and everything in it):

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

Last modified: 10/31/2016 at 21:44 by jean f.