A Linux Playground

My doodles and what I get up to.

Setting Up Password Protected Website With Htaccess

Running a website it is often useful to password protect areas of your site. If the area is not using php and is a simple site using html links to files that can be downloaded using https then a .htaccess file is the way to go.

Setup

First off start by putting a file titled “.htaccess” into the directory you would like restricted. It should contain the following lines

1
2
3
4
5
.htaccess
AuthType Basic
AuthName "Authorisation Required."
AuthUserFile  /etc/apache2/htpasswd
Require valid-user

Next create a password file to store the credential of the people you want to allow into said area. You create the file by issuing the following with your first username. The -c option creates a new file.

1
sudo htpasswd -c  /etc/apache2/htpasswd username

It will ask you to enter a password and to it repeat to ensure you typed it correctly. Subsequent users can be added by the same command but used without the -c flag. Using the -c flag creates or overwrites the file. Next we need to ensure that only the Apache server can read the file. (assumes that www-data is the Apache server group)

1
2
sudo chown :www-data /etc/apache2/htpasswd
sudo chmod 740  /etc/apache2/htpasswd

Lastly Apache needs to be told that the .htaccess files in directories should be acted upon. This is done by editing the file /etc/apache2/sites- available/default. Where it says AllowOverride None change it to AllowOverride All. Lastly reload Apache and it will start asking you for a password when entering that directory.

1
sudo service apache2 reload

Note: unless the site is using https the passwords will be sent in clear text.