When developing websites, you sometimes need to hide the whole site behind a simple login. This may be for testing purposes or in situations where building a more complex authentication mechanism is not worth it.
Setting up HTTP Basic Authentication is very simple and quick. Basically, all we need to do is generate a file with login credentials and add a few lines to the Apache configuration – either directly to the VirtualHost definition or to an .htaccess file.
We create the credentials file with the htpasswd command right on the server (do not use online generators – you would be sending the password to a third-party service):
$ htpasswd -cB .htpasswd username
The command asks for the password twice and creates the .htpasswd file directly in the current directory, so the password does not end up in your shell history. The -cB parameters used mean:
- c - create the specified file; if it already exists, it will be overwritten
- B - store the password as a bcrypt hash
Then all that remains is to require authentication in the Apache server, which must have the auth_basic module enabled. If it is not enabled and we have root access, we can easily enable it with the command:
a2enmod auth_basic
The actual authentication configuration can be placed in the VirtualHost definition inside the <Directory> directive:
<Directory /some/path>
...
AuthType Basic
AuthName "Login required"
AuthUserFile /absolute/path/to/.htpasswd
Require valid-user
# If you want to allow only a specific user to log in
# Require user username
</Directory>
It is important to specify the path to the authentication file as an absolute path.
If we are going to put it in .htaccess, we need to check that changing settings via .htaccess is allowed for the given <Directory>. The AllowOverride directive must be set to either AuthConfig or All:
<Directory /some/path>
...
AllowOverride AuthConfig
</Directory>
Then just add the following to .htaccess:
AuthType Basic
AuthName "Login required"
AuthUserFile /absolute/path/to/.htpasswd
Require valid-user
Basic Authentication in the Apache server of course offers many more features and configuration options. You can go through the complete documentation in the official documentation