0
0
NginxHow-ToBeginner · 3 min read

How to Use htpasswd with Nginx for Basic Authentication

To use htpasswd with nginx, first create a password file using the htpasswd command. Then configure your nginx server block to use auth_basic and auth_basic_user_file directives pointing to that file to enable basic authentication.
📐

Syntax

The htpasswd command creates or updates a file storing usernames and encrypted passwords. The basic syntax is:

  • htpasswd -c /path/to/.htpasswd username - Creates a new password file and adds the user.
  • htpasswd /path/to/.htpasswd username - Adds or updates a user in an existing file.

In the nginx configuration, use:

  • auth_basic "Message"; - Enables basic auth with a prompt message.
  • auth_basic_user_file /path/to/.htpasswd; - Points to the password file.
bash
htpasswd -c /etc/nginx/.htpasswd username

# nginx.conf snippet inside server or location block
location /secure/ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
💻

Example

This example shows how to create a password file and configure nginx to protect a directory with basic authentication.

bash
# Create password file and add user 'alice'
htpasswd -c /etc/nginx/.htpasswd alice

# nginx configuration snippet
server {
    listen 80;
    server_name example.com;

    location /secure/ {
        auth_basic "Please enter your credentials";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}
Output
New password: Re-type new password: Adding password for user alice
⚠️

Common Pitfalls

  • Forgetting to use -c only when creating the file first time; using it again overwrites the file.
  • Incorrect file permissions on the .htpasswd file can prevent nginx from reading it.
  • Not reloading or restarting nginx after changing configuration causes no effect.
  • Using relative paths instead of absolute paths in auth_basic_user_file can cause errors.
bash
# Wrong: overwriting file unintentionally
htpasswd -c /etc/nginx/.htpasswd bob  # Use -c only once

# Right: add user without overwriting
htpasswd /etc/nginx/.htpasswd bob
📊

Quick Reference

Command/DirectivePurpose
htpasswd -c /path/.htpasswd usernameCreate new password file with user
htpasswd /path/.htpasswd usernameAdd or update user in existing file
auth_basic "Message";Enable basic auth with prompt message
auth_basic_user_file /path/.htpasswd;Specify password file location

Key Takeaways

Create the password file with htpasswd -c only once to avoid overwriting.
Use absolute paths for the .htpasswd file in nginx configuration.
Set proper file permissions so nginx can read the password file.
Reload nginx after configuration changes to apply authentication.
Basic auth with htpasswd is simple and effective for protecting resources.