Skip to content
iD-SIGN
Contact us

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.

2 min readpublished 7/2021

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):

bash
$ 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:

bash
a2enmod auth_basic

The actual authentication configuration can be placed in the VirtualHost definition inside the <Directory> directive:

apache
<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:

apache
<Directory /some/path>
    ...
    AllowOverride AuthConfig
</Directory>

Then just add the following to .htaccess:

apache
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

Tags Servers, Linux, Apache

Share LinkedIn Facebook

Need more than an article?

A few sentences about what you are dealing with are enough.