HTTP Basic Auth with Apache server and .htaccess
A simple and quick way to put a website behind a login if you use the Apache web server.
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.
Creating the credentials file is easy. We can either use an online service, e.g. https://hostingcanada.org/htpasswd-generator/, or use the htpasswd command:
$ htpasswd -bcB .htpasswd username password
This generates the .htpasswd file directly in the current directory, and the -bcB parameters used mean:
- b - the password is entered directly in the command
- c - create the specified file
- B - use bcrypt to encrypt the password
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