Skip to content

Blog

Keycloak behind a proxy: fixing 502s and redirect loops

Why Keycloak behind nginx or a load balancer returns 502, 403 or loops between URLs, and how hostname, proxy headers, buffers and health checks fix it.

Author
The RealmDeploy team
Published

Keycloak almost always runs behind something: nginx, HAProxy, Traefik, a cloud load balancer or a Kubernetes ingress. The proxy holds the certificate and passes requests on. Keycloak then has to know two things it cannot see for itself: the public address people use, and whether they came over HTTPS.

When that goes wrong, the symptoms are loud. The proxy answers 502 Bad Gateway. The browser bounces between two URLs until it gives up. The sign-in page loads without styles, or redirects to http:// and an internal host name.

This post walks through the causes in the order we see them, how to tell them apart, and what to change. Everything here applies to Keycloak 26.x.

What you see

  • 502 Bad Gateway or 504 Gateway Timeout from the proxy, usually right after a sign-in form is submitted or on the callback to your app.
  • A redirect loop. The browser reports too many redirects, or the network tab shows the same two URLs repeating.
  • Redirects to http:// or to an internal address such as keycloak:8080, even though users open an https:// URL.
  • 403 Forbidden on requests that check the origin, such as admin console calls.
  • In nginx's error log, the line upstream sent too big header while reading response header from upstream.
  • In the browser, "HTTPS required" on the sign-in page. We cover that one in its own post: HTTPS required.

Causes, most common first

  1. hostname is missing or not a full URL. Discovery shows the wrong scheme, host or port for the issuer and endpoints.
  2. proxy-headers is not set, or does not match the proxy. Keycloak's guide says that without it you will see 403 responses to requests that perform origin checking.
  3. The proxy does not send X-Forwarded-Proto, or sends http. Keycloak builds http:// URLs, and an HTTP to HTTPS redirect at the proxy sends the browser around in a loop.
  4. Response headers are larger than the proxy's buffer. nginx logs "upstream sent too big header" and returns 502 after sign-in.
  5. The proxy points at the wrong port. Traffic goes to 8443 over plain HTTP, or to the management port 9000.
  6. TLS ends at the proxy, but HTTP is not enabled in Keycloak. Production mode serves only HTTPS unless http-enabled is true, so a plain HTTP upstream fails.
  7. The context path differs. The proxy serves /auth but Keycloak serves /, or the other way around.
  8. Timeouts or health checks. The proxy marks nodes down, or gives up before a slow request finishes.

Diagnose it step by step

  1. Open the discovery document through the public URL and read the issuer. It should be exactly https://<your host>/realms/<realm>.

    curl -s https://auth.example.com/realms/acme/.well-known/openid-configuration \
      | jq -r '.issuer, .authorization_endpoint'
    
  2. Follow the redirects with curl and watch every Location header. A switch to http:// or to an internal host shows where it breaks.

    curl -sI -L --max-redirs 10 \
      'https://auth.example.com/realms/acme/account' | grep -i '^location'
    
  3. Read the proxy's error log at the time of a 502. nginx says why it gave up: buffer size, connection refused, or timeout.

  4. Check what Keycloak receives. Turn on the hostname debug page for a short time with --hostname-debug=true, then open /realms/<realm>/hostname-debug through the proxy. It shows how Keycloak resolved each URL.

  5. Check the configuration Keycloak really uses with bin/kc.sh show-config, and read the Keycloak log at the time of the failure for errors.

  6. Open the network tab in the browser. Note which request returns 502 and how large its cookies are. A sign-in response sets several cookies, and some apps add more of their own.

  7. Turn on saved events in the admin console (Realm settings, Events). A loop that ends in your app may be an app-side error after a good login, such as an issuer check that fails.

Fixes

Set the public address as a full URL

In Keycloak 26, hostname accepts a full URL. Behind a proxy on the default HTTPS port, use the full URL so the scheme and port are fixed:

bin/kc.sh start \
  --hostname=https://auth.example.com \
  --http-enabled=true \
  --proxy-headers=xforwarded

http-enabled=true is needed when TLS ends at the proxy and the proxy talks HTTP to Keycloak on port 8080. Keycloak's hostname guide shows the same combination for edge TLS termination.

Older setups used proxy=edge. That option is gone in Keycloak 26. Use http-enabled and proxy-headers instead.

Pick the proxy header mode that matches the proxy

proxy-headers takes xforwarded for the X-Forwarded-* headers or forwarded for the standard Forwarded header. Choose the one your proxy sets, and make sure the proxy overwrites it rather than passing on what the client sent. Otherwise anyone can claim any address or scheme.

Limit trust to the proxy's address when it is stable:

bin/kc.sh start --proxy-headers=xforwarded \
  --proxy-trusted-addresses=10.0.0.10,10.0.1.0/24

Headers from other addresses are then ignored. Do not set proxy-headers at all with TLS passthrough. The proxy cannot add headers to encrypted traffic, so any such header came from the client.

A working nginx block

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

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

    # Keycloak's sign-in responses carry large cookies.
    proxy_buffer_size       128k;
    proxy_buffers           4 256k;
    proxy_busy_buffers_size 256k;

    location ~ ^/(realms|resources)/ {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host              $host;
        proxy_set_header X-Forwarded-For   $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host  $host;
        proxy_set_header X-Forwarded-Port  $server_port;
    }
}

server {
    listen 80;
    server_name auth.example.com;
    return 301 https://$host$request_uri;
}

Setting X-Forwarded-For to $remote_addr overwrites the client's value. If another trusted proxy sits in front of nginx, adjust that line to keep its value instead.

This block exposes only /realms/ and /resources/. Keycloak's reverse proxy guide recommends keeping /admin/ internal and not exposing /realms/master/ to the public internet. If you do need the admin console on this host, add /admin/ deliberately.

Fix 502s from large headers

The nginx line upstream sent too big header while reading response header from upstream means a response header block did not fit in proxy_buffer_size. Raise the buffers as above and reload nginx. Other proxies have similar limits under other names. Check the request side too: a browser that sends many large cookies can hit the proxy's request header limit.

Point at the right port

Keycloak serves sign-in, tokens, the account console and the admin API on 8080 (with http-enabled) or 8443. Health checks and metrics live on the management port, 9000 by default. Proxy the first, never the second.

For a load balancer health check, use the management port from inside the network:

bin/kc.sh start --health-enabled=true
curl -s http://127.0.0.1:9000/health/ready

A check aimed at a sign-in page can mark healthy nodes down, which looks like random 502s. Point it at /health/ready on port 9000 instead.

Match the context path

Keycloak 17 and later serve at / by default. If clients still use /auth/realms/..., choose one of the options from Keycloak's guide:

  • Put the path in the hostname: --hostname=https://auth.example.com/auth, and have the proxy strip or map it.
  • Change Keycloak's own path: --http-relative-path=/auth, and proxy /auth/ straight through.
  • Use xforwarded with a plain host name and have the proxy send X-Forwarded-Prefix.

Pick one. Mixing them is a common source of loops.

Give slow requests time

Imports, large admin queries and first starts after an upgrade can take longer than a proxy's default read timeout. If the proxy logs a timeout, raise it for Keycloak's location, for example proxy_read_timeout in nginx. Do not raise it blindly for every path.

On Kubernetes

An ingress controller or Gateway API implementation plays the proxy role. The same rules apply: set hostname, http-enabled and proxy-headers on Keycloak, route /realms/ and /resources/, and point health probes at port 9000. Ingress buffer settings use annotations or policies instead of nginx directives.

On RealmDeploy

We run the proxy layer for you. Each tenant's Keycloak has hostname set to https:// plus your own hostname, TLS ends at our shared Envoy Gateway, and Keycloak runs with http-enabled=true and proxy-headers=xforwarded. Envoy drops any X-Forwarded-* headers the client sends and sets its own. Plain HTTP to your hostname is redirected to HTTPS.

The buffer between Envoy and Keycloak is 128 KiB per connection, and Envoy's own header limits are 60 KiB for request headers and for response headers. If your app sets large cookies on the same domain, keep them well under that.

If you put your own proxy or CDN in front of your RealmDeploy hostname, the rules above apply to that layer. If you see a 502 or a loop on your hostname, write to us from the dashboard or with the contact form, with the time, the URL and what the browser showed. See Custom domains and TLS and Architecture for how requests reach your Keycloak.

Tools that help