python network_error ai_generated true

starlette.middleware.trustedhost.InvalidHost: Invalid host header

ID: python/starlette-trustedhost-invalid-host

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-09-11First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

TrustedHostMiddleware is enabled but the request Host header is not in the allowed_hosts list (common behind proxies or on localhost).

generic

中文

启用了 TrustedHostMiddleware,但请求的 Host 头不在 allowed_hosts 列表中(在代理后或 localhost 上常见)。

Workarounds

  1. 93% success
    app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', '*.example.com'])
  2. 87% success
    from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
    app.add_middleware(ProxyHeadersMiddleware, trusted_hosts='*')

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Disables host header protection entirely.

  2. 80% fail

    Deployed environments still reject proxy hosts.