python config_error ai_generated true

starlette.middleware.trustedhost: Invalid host header: 'evil.example.com'

ID: python/starlette-trustedhost-invalid-host-header

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2025-02-11First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

TrustedHostMiddleware rejects requests whose Host header isn't in allowed_hosts, common behind proxies with wrong host forwarding.

generic

中文

TrustedHostMiddleware 拒绝 Host 头不在 allowed_hosts 中的请求,常见于代理未正确转发 Host。

Workarounds

  1. 88% success
    Configure proxy to forward Host, and list real hosts:
    app.add_middleware(TrustedHostMiddleware, allowed_hosts=['api.example.com'])
  2. 82% success
    Use ProxyHeadersMiddleware/forwarded headers in the ASGI server config.

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Disables the protection entirely, defeating the middleware purpose.

  2. 70% fail

    Reopens host header injection and loses the security control.