0
0
NginxHow-ToBeginner · 4 min read

How to Configure Basic Auth in Nginx: Simple Guide

To configure basic auth in nginx, create a password file using htpasswd, then add auth_basic and auth_basic_user_file directives inside your server or location block. This setup prompts users for a username and password before accessing the protected content.
📐

Syntax

The basic auth configuration in nginx uses two main directives:

  • auth_basic "Message"; - This enables basic authentication and sets the prompt message shown to users.
  • auth_basic_user_file /path/to/.htpasswd; - This points to the file containing usernames and encrypted passwords.

Place these directives inside a server or location block to protect that area.

nginx
location /protected/ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
💻

Example

This example shows how to protect the /admin path with basic auth. First, create a password file with htpasswd. Then configure nginx to use it.

bash and nginx
# Create password file with user 'admin'
htpasswd -c /etc/nginx/.htpasswd admin

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

    location /admin {
        auth_basic "Admin Login";
        auth_basic_user_file /etc/nginx/.htpasswd;

        root /var/www/html;
        index index.html;
    }
}
Output
New password: Re-type new password: Adding password for user admin # After reload, accessing http://example.com/admin prompts for username and password.
⚠️

Common Pitfalls

  • Not creating the .htpasswd file or placing it in a wrong path causes authentication to fail.
  • Forgetting to reload or restart nginx after changes means new settings won't apply.
  • Using auth_basic off; inside a protected block disables authentication unexpectedly.
  • File permissions on .htpasswd must allow nginx to read it.
nginx
location /secure/ {
    # Wrong: auth_basic off disables auth
    auth_basic off;
    auth_basic_user_file /etc/nginx/.htpasswd;
}

# Correct way:
location /secure/ {
    auth_basic "Secure Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
📊

Quick Reference

DirectivePurposeExample
auth_basicEnable basic auth and set prompt messageauth_basic "Login Required";
auth_basic_user_filePath to password fileauth_basic_user_file /etc/nginx/.htpasswd;
htpasswdCommand to create password filehtpasswd -c /etc/nginx/.htpasswd username
nginx -s reloadReload nginx to apply changessudo nginx -s reload

Key Takeaways

Create a password file with htpasswd before configuring nginx.
Use auth_basic and auth_basic_user_file directives inside server or location blocks.
Reload nginx after configuration changes to apply them.
Ensure nginx can read the .htpasswd file with correct permissions.
Avoid disabling auth_basic inside protected blocks unless intended.