> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Authentication

> Adding HTTP Basic Authentication to NGINX to protect an /admin endpoint using an .htpasswd file, password hashing, and config validation

In this guide you'll add HTTP Basic Authentication to an NGINX server so the public site remains available at:

`https://www.example.com`

but a specific endpoint `/admin` requires a username and password. This is a lightweight protection method ideal for internal tools, staging sites, or quick demos.

![A person sits at a desk using a laptop with a dotted arrow pointing to a web admin sign-in page showing password fields and a padlock. The illustration represents logging into or securing an admin portal.](https://mintcdn.com/kodekloud-c4ac6d9a/x1wBthvq78ZWHRHX/images/Nginx-for-Beginners/Security/Demo-Authentication/admin-portal-login-illustration.jpg?fit=max\&auto=format\&n=x1wBthvq78ZWHRHX\&q=85\&s=a854278bed46af2ab60cbc87a2e013c3)

Overview

* Keep the main site open to everyone.
* Add a `location /admin` block and enable `auth_basic`.
* Store credentials in an `.htpasswd` file and point NGINX to that file.
* Validate and reload NGINX, then verify the browser prompt.

Quick steps at a glance:

| Step | Purpose | Example / Command |
| - | - | - |
| Configure NGINX | Protect `/admin` with basic auth | Add `auth_basic` and `auth_basic_user_file` to `location /admin` |
| Create credentials | Generate an APR1-MD5 hash | `openssl passwd -apr1` |
| Test & reload | Validate and apply the config | `sudo nginx -t && sudo nginx -s reload` |

Prerequisites

* NGINX installed and serving `https://www.example.com`.
* Root or sudo access to modify NGINX config and write to `/etc/nginx/conf.d/`.
* OpenSSL (for quick password hashing) or `htpasswd` from `apache2-utils` / `httpd-tools`.

1 — Protect the `/admin` endpoint
Add a `location /admin` block to the TLS server block (listen 443) and enable basic auth only for that location.

Example server block (replace certificate paths and `server_name` as appropriate):

```nginx theme={null}
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/ssl/certs/example.com.pem;
    ssl_certificate_key /etc/ssl/certs/example.com-key.pem;

    root /var/www/html;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
    add_header X-Frame-Options "SAMEORIGIN";
    add_header Content-Security-Policy "default-src 'self'";
    add_header Referrer-Policy origin;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

    location /admin {
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/conf.d/.htpasswd;
    }
}
```

Placing the `auth_basic` directives in `location /admin` protects only that path. To require authentication for the entire site, move `auth_basic` and `auth_basic_user_file` into the `location /` block or directly under the `server` block.

2 — Create the `.htpasswd` file
Create `/etc/nginx/conf.d/.htpasswd` and add a user `admin` with an APR1-MD5 hashed password. The example below writes the `admin:` prefix first, then appends the hash generated by OpenSSL.

Commands:

```bash theme={null}
# Create the file with the username prefix (no newline)
sudo sh -c "echo -n 'admin:' > /etc/nginx/conf.d/.htpasswd"

# Append an APR1-MD5 password hash to the file (you will be prompted for the password)
sudo sh -c "openssl passwd -apr1 >> /etc/nginx/conf.d/.htpasswd"
```

Example `.htpasswd` content:

```text theme={null}
admin:$apr1$MASb7ZA.$b8LOCauVuqug5nH2AIk72/
```

Notes on credential management

* The `.htpasswd` stores a one-way hash (you cannot recover the plaintext password from the hash).
* For more features (user management, easier password creation), use the `htpasswd` utility from the Apache packages:
  * Debian/Ubuntu: `apache2-utils`
  * CentOS/RHEL: `httpd-tools`
* Keep the `.htpasswd` file readable by the NGINX process user and placed outside webroot (e.g., `/etc/nginx/conf.d/.htpasswd`) to avoid accidental exposure.

3 — Test and reload NGINX
Validate the configuration and reload NGINX:

```bash theme={null}
sudo nginx -t
sudo nginx -s reload
```

After reloading, open `https://www.example.com/admin` in a browser. You should see an authentication prompt. Provide `admin` and the password you entered when creating the hash.

![A web browser window displaying a small "Sign in" dialog near the top center with fields for Username and Password and Cancel/Sign In buttons. The rest of the page is mostly blank white, with a URL visible in the address bar.](https://mintcdn.com/kodekloud-c4ac6d9a/x1wBthvq78ZWHRHX/images/Nginx-for-Beginners/Security/Demo-Authentication/browser-sign-in-dialog-top-center.jpg?fit=max\&auto=format\&n=x1wBthvq78ZWHRHX\&q=85\&s=26bb445cd096dde2d6d63da90171002a)

Optional — Protect the entire site
To require authentication for all paths, add the auth directives to `location /` (or `server`) instead of `location /admin`:

```nginx theme={null}
location / {
    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/conf.d/.htpasswd;
    try_files $uri $uri/ =404;
}
```

Testing tips

* Browsers cache Basic Auth credentials for the session. Use an incognito/private window or a different browser to test the login prompt cleanly.
* If tests fail, check NGINX error logs (typically `/var/log/nginx/error.log`) for hints.

Basic authentication is convenient for quick internal protection or demos but is not sufficient for most production systems. It doesn't scale for large user bases, lacks centralized identity management, fine-grained access controls, and multi-factor authentication. For production, prefer centralized identity providers (OAuth, OpenID Connect, SAML) or integrate with LDAP/Active Directory and always use TLS.

NGINX Plus and advanced integrations

* NGINX Plus and third-party modules provide richer authentication options (OpenID Connect, OAuth, external identity providers).
* Example of loading the NGINX JavaScript module:

```nginx theme={null}
load_module modules/ngx_http_js_module.so;
```

* Installing njs (module names vary by distribution and edition):

```bash theme={null}
# Debian/Ubuntu (package names vary)
sudo apt install nginx-plus-module-njs

# CentOS/RHEL (package names vary)
sudo yum install nginx-plus-module-njs
```

If integrating with Okta, Azure AD, or similar identity providers, consult provider docs and NGINX Plus documentation for flow examples and required modules.

Summary

* You protected a single endpoint (`/admin`) using `auth_basic` and an `.htpasswd` file.
* You generated an APR1-MD5 password hash with OpenSSL and reloaded NGINX.
* For production-grade security, plan for centralized authentication systems and stronger access controls.

Links and references

* [NGINX Documentation](https://nginx.org/en/docs/)
* [htpasswd utility (Apache)](https://httpd.apache.org/docs/current/programs/htpasswd.html)
* [OpenSSL passwd manual](https://www.openssl.org/docs/man1.1.1/man1/openssl-passwd.html)

> **[Watch Video](https://learn.kodekloud.com/user/courses/nginx-for-beginners/module/8905470e-b1ea-48ec-b0cd-711687ce7159/lesson/3264362e-1f24-419d-9a96-d225e7708fd1)**

> **[Practice Lab](https://learn.kodekloud.com/user/courses/nginx-for-beginners/module/8905470e-b1ea-48ec-b0cd-711687ce7159/lesson/3898f285-8614-4509-86f8-16bc73f921ea)**


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.