AIForum.

How to Set Up a Reverse Proxy with Bearer Token Authentication for a Local AI Server

On this page

THE SHORT ANSWER

Put a reverse proxy in front of your local AI server to enforce TLS and require an Authorization: Bearer token on every request. This guide covers the architecture, Nginx and Caddy examples, verification with curl, and common errors. Ollama and similar runtimes listen without built-in authentication on ports such as 11434, so the proxy becomes the security boundary.
Quick facts

If your local AI server is reachable beyond localhost, a reverse proxy with Bearer token authentication is the simplest way to add a security boundary. The proxy terminates TLS, checks the Authorization: Bearer <token> header, and only then forwards requests to the model runtime. This pattern works with Ollama, llama.cpp server, vLLM, and similar backends that expose an HTTP API but do not include built-in authentication.

Ollama, for example, listens on port 11434 by default and has no built-in authentication. Without a reverse proxy, anyone who can reach that port has unrestricted access to your models. A reverse proxy can provide TLS encryption, authentication, rate limiting, and access control. The Nginx reverse proxy guide describes the reverse proxy as a central security shield for local GPU compute, while the Caddy reverse proxy documentation notes that authentication can be Basic Auth or a Bearer token.

How the proxy fits between clients and the model server

The request path is: client application → reverse proxy (HTTPS, port 443) → local model server (HTTP, localhost:11434 or similar). The proxy performs three jobs before forwarding:

  • TLS termination: encrypts traffic between the client and the proxy. Without TLS, a Bearer token is sent in clear text.
  • Authentication: compares the Authorization header against a known token. If it does not match, the proxy returns 401 Unauthorized and never contacts the backend.
  • Reverse proxying: forwards allowed requests to the backend, preserving streaming responses where needed.

This keeps the model runtime bound to 127.0.0.1 and off the public network. The proxy becomes the only exposed service.

Prerequisites

  • A local AI server already running on the host. The examples assume Ollama on localhost:11434, but you can change the port for llama.cpp, vLLM, or another HTTP API.
  • A reverse proxy installed: Nginx or Caddy.
  • A domain name pointed at the proxy host if you want automatic TLS via Let’s Encrypt. For internal networks, a self-signed certificate or a private CA is an alternative.
  • A long, random token. A common method is openssl rand -hex 32. Store it in a secret manager or an environment variable, not in a public repository.

Option A: Caddy with a Bearer token check

Caddy is often chosen for local AI because it can provision and renew TLS certificates automatically from Let’s Encrypt when a public domain is available. The supplied Caddy documentation demonstrates Basic Auth with the basicauth directive and mentions Bearer token as an authentication option, but it does not include a Bearer-token configuration example. The following Caddyfile is an illustrative header-matcher pattern; verify it against your Caddy version before production use.

ai.example.com {
    @authorized header Authorization "Bearer YOUR_TOKEN"
    handle @authorized {
        reverse_proxy localhost:11434
    }
    respond 401
}

In this configuration, Caddy listens on ai.example.com, checks for the exact Authorization header, and forwards matching requests to Ollama. Requests without the header receive 401. For internal-only deployments, replace the site address with an internal hostname and configure a self-signed certificate or use Caddy’s internal CA.

If you prefer the documented Basic Auth path, the Caddy source shows generating a bcrypt hash with caddy hash-password and adding a basicauth block. Bearer tokens are usually a better fit for API clients because they avoid sending a username and password on every request, but both methods rely on TLS for confidentiality.

Option B: Nginx with a Bearer token check

Nginx gives you fine-grained control and is already present in many self-hosted stacks. The Nginx guide in the references covers reverse proxy authentication for a local LLM; the following is a standard Nginx implementation you can adapt. It uses a map to turn the Authorization header into an allow/deny flag.

map $http_authorization $api_auth {
    default 0;
    "Bearer YOUR_TOKEN" 1;
}

server {
    listen 443 ssl;
    server_name ai.example.com;

    ssl_certificate /etc/letsencrypt/live/ai.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/ai.example.com/privkey.pem;

    location / {
        if ($api_auth = 0) {
            return 401;
        }

        proxy_pass http://127.0.0.1:11434;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Local AI responses can stream for a long time.
        proxy_buffering off;
        proxy_read_timeout 300s;
        client_max_body_size 20m;
    }
}

Replace YOUR_TOKEN with the value you generated. Keep the map block in the http context, not inside server. If you manage multiple tokens, you can move the token lines into an included file and reload Nginx after rotation.

For TLS, you can use Let’s Encrypt with Certbot or a certificate from your internal CA. The Nginx source emphasizes that the proxy is the layer that enforces authentication before requests reach the GPU compute.

Verify the setup with curl

After reloading the proxy, test both the failure and success paths. The exact API path depends on your backend; Ollama exposes endpoints such as /api/tags.

# Should return 401 Unauthorized
curl -i https://ai.example.com/api/tags

# Should return 200 and JSON listing local models
curl -i -H "Authorization: Bearer YOUR_TOKEN" https://ai.example.com/api/tags

If the second command succeeds, the proxy is forwarding correctly. You can also test streaming with a chat completion endpoint and curl -N to confirm that tokens arrive incrementally rather than all at once. Check the proxy access log and the backend log to confirm that allowed requests reach the model server and rejected requests do not.

Common errors and fixes

  • 401 Unauthorized on every request: The token does not match exactly. Check for extra spaces, missing Bearer prefix, or case differences. The header name is Authorization; the scheme is usually case-sensitive in practice.
  • 502 Bad Gateway: The proxy cannot reach the backend. Confirm the model server is running, the port is correct, and the proxy is using 127.0.0.1 or the correct internal address.
  • 413 Payload Too Large: Large prompts or file uploads exceed Nginx’s default body size. Increase client_max_body_size in the relevant server or location block.
  • Timeouts during long generations: Increase proxy_read_timeout and disable proxy_buffering for streaming responses.
  • Streaming stalls: Buffering can hold tokens until the response completes. Turn off proxy buffering and verify that the backend supports streaming through the proxy.
  • TLS certificate errors: For public domains, confirm DNS points to the proxy and that port 80 or 443 is reachable for ACME challenges. For internal names, install your CA certificate on clients.

Security and operational tradeoffs

A Bearer token is a shared secret. Anyone who obtains it can use your GPU compute. Treat tokens like passwords: use long random values, rotate them periodically, and issue separate tokens per user or application when possible. Because the token is sent in the Authorization header, TLS is mandatory. Without TLS, the token can be captured on the network.

A reverse proxy also introduces a single point of failure and an extra network hop. For a single-user workstation, the benefit is mainly safe remote access and a clean API boundary. For a shared lab or home server, the proxy enables rate limiting, IP allowlists, and audit logging. The Caddy source notes that rate limiting and access control are part of the reason to use a reverse proxy at all.

Basic Auth and Bearer tokens solve different ergonomics. Basic Auth is easy to test in a browser and is documented in the Caddy example. Bearer tokens are more common for API clients and are easier to rotate without changing a username. Neither is a substitute for TLS, and neither provides per-user authorization by itself.

Next steps

Once the proxy is working, add rate limiting, restrict access by IP where possible, and log authentication failures. Keep the model backend bound to 127.0.0.1 so the proxy remains the only entry point. If you run multiple models or users, consider separate tokens and a small access policy rather than one shared secret.

If you try this setup, share your environment (proxy, backend, OS) and the exact error or result in the community. Reproducible notes about streaming behavior, timeouts, and token rotation help other local AI practitioners.

FAQ

Can Ollama authenticate users by itself?

No. Ollama has no built-in authentication. When exposing it beyond localhost, a reverse proxy provides authentication, TLS, and access control.

Is Bearer token authentication better than Basic Auth?

Neither is inherently better. Both must run over TLS. Bearer tokens are often easier for API clients and rotation; Basic Auth is simpler for browser prompts and is explicitly documented in the Caddy example.

How do I test the proxy without a browser?

Use curl with and without the Authorization header. A request without the header should return 401; a request with the correct Bearer token should return the backend API response.

What Nginx directive handles large prompts?

Increase client_max_body_size in the server or location block. The default may be too small for large file uploads or long prompts.

Does the proxy need to support streaming?

Yes, for chat and completion endpoints. Disable proxy buffering in Nginx and confirm the backend streams through the proxy.

References

  1. https://gids.llmnet.nl/en/nginx-reverse-proxy-met-authenticatie-voor-je-lokale-llm
  2. https://github.com/meganerd/electrictown/blob/main/docs/caddy-reverse-proxy.md

Related terms

Reverse proxy
A server that sits in front of backend services and forwards client requests after applying policies such as TLS and authentication.
Bearer token
A credential sent in the Authorization header using the Bearer scheme, typically as a shared secret for API access.
TLS termination
The process of decrypting HTTPS traffic at the proxy before forwarding it to an internal service.
Ollama
A local model runtime that exposes an HTTP API on port 11434 by default and has no built-in authentication.
Basic Auth
An authentication method that sends a base64-encoded username and password; documented in the Caddy example.

Leave a Reply

Your email address will not be published. Required fields are marked *