Basic authentication for Apache
Prerequisites
We need to ensure that the htpasswd utility is installed. Try to run it from the command line, otherwise install it;
sudo apt-get install apache2 apache2-utils
Enable basic authentication
A minimalistic virtual host configuration will look like this:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Authentication is defined on a per-directory basis. To set up authentication, a target directory has to be defined using the <Directory /xxx/yyy/ > block.
Within this directory block, specify that Basic authentication should be used. Select a realm name, which will be displayed to the user when prompting for credentials, using the AuthName directive. Use the AuthUserFile directive to point Apache to the password file which will created. Finally, specify that a valid-user is required to access this resource, which means anyone who can verify their identity with a password will be allowed in.
For example
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory "/var/www/html">
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>
</VirtualHost>
Save and close the file, then restart Apache to implement your password policy:
sudo service apache2 restart
The directory specified should now be password protected.
AuthType Basic
AuthName "Access by invitation only"
AuthBasicProvider file
AuthUserFile "/usr/local/apache/passwd/passwords"
AuthGroupFile "/usr/local/apache/passwd/groups"
Require group GroupName
Create the Password File
A password file should be created to store the usernames and passwords for Apache to use. A file can be created per virtual host or share amongst many sites.
| The file should be created outside the site content to prevent access via the browser. A good location is in the /etc/apache2 configuration directory. |
When creating the file for the first time the -c option should be used. Specify a username at the end of the command to create a new entry within the file:
sudo htpasswd -c /etc/apache2/.htpasswd <username>
The command will ask to supply and confirm a password for the user.
For subsequent users the -c argument can be omitted, which will append users to the file, for example;
sudo htpasswd /etc/apache2/.htpasswd <username>