Beginner Fundamentals

Basic Authentication

Basic authentication asks visitors for a username and password before showing protected content. Apache checks the credentials against a password file.

Create a Password File

The htpasswd tool creates and manages the file. The -c flag creates a new file:

sudo htpasswd -c /etc/apache2/.htpasswd admin

Add more users without -c so you do not overwrite the file:

sudo htpasswd /etc/apache2/.htpasswd editor

Protect a Directory

<Directory /var/www/private>
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /etc/apache2/.htpasswd
    Require valid-user
</Directory>
  • AuthType Basic: use HTTP basic authentication.
  • AuthName: the message shown in the login prompt.
  • Require valid-user: any listed user may log in.

Restrict to One User

Require user admin

Apply Changes

sudo apache2ctl configtest
sudo systemctl reload apache2

Basic auth sends passwords with weak encoding, so always use it together with HTTPS to keep credentials safe.