0
0
NginxHow-ToBeginner · 3 min read

How to Use auth_basic in Nginx for Simple HTTP Authentication

Use auth_basic to enable basic HTTP authentication in Nginx by specifying a realm name and auth_basic_user_file to point to a password file. This setup prompts users for a username and password before accessing protected content.
📐

Syntax

The auth_basic directive enables basic authentication and sets the authentication realm shown in the login prompt. The auth_basic_user_file directive specifies the path to the password file containing usernames and encrypted passwords.

Example parts:

  • auth_basic "Restricted Area"; sets the realm name.
  • auth_basic_user_file /etc/nginx/.htpasswd; points to the password file.
nginx
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
💻

Example

This example shows how to protect the /secure location on your website using basic authentication. Users will be prompted to enter a username and password stored in /etc/nginx/.htpasswd.

nginx
server {
    listen 80;
    server_name example.com;

    location /secure {
        auth_basic "Restricted Area";
        auth_basic_user_file /etc/nginx/.htpasswd;

        root /var/www/html;
        index index.html;
    }
}
Output
When accessing http://example.com/secure, the browser prompts for username and password. Access is granted only if credentials match those in /etc/nginx/.htpasswd.
⚠️

Common Pitfalls

Common mistakes when using auth_basic include:

  • Not creating or incorrectly formatting the password file. Use htpasswd tool to create it.
  • Incorrect file permissions on the password file, causing Nginx to fail reading it.
  • Placing auth_basic directives in the wrong context (e.g., outside location or server blocks).
  • Forgetting to reload or restart Nginx after configuration changes.

Wrong example (missing password file):

location /secure {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/missing.htpasswd;
}

Right example (correct file path and permissions):

location /secure {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
📊

Quick Reference

Summary tips for using auth_basic:

  • Use htpasswd to create and manage password files.
  • Set proper file permissions so Nginx can read the password file.
  • Place auth_basic directives inside location or server blocks.
  • Reload Nginx after changes with nginx -s reload.

Key Takeaways

Enable basic authentication with auth_basic and specify a realm name.
Use auth_basic_user_file to point to a valid password file created by htpasswd.
Place authentication directives inside location or server blocks.
Ensure correct file permissions and reload Nginx after configuration changes.
Basic auth prompts users for credentials before allowing access to protected content.