python config_error ai_generated true

starlette.middleware.trustedhost: 无效的 Host 头:'evil.example.com'

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
83%置信度
0证据数
2025-02-11首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 60% 失败

    Disables the protection entirely, defeating the middleware purpose.

  2. 70% 失败

    Reopens host header injection and loses the security control.