python
network_error
ai_generated
true
starlette.middleware.trustedhost.InvalidHost: 无效的 Host 头
starlette.middleware.trustedhost.InvalidHost: Invalid host header
ID: python/starlette-trustedhost-invalid-host
80%修复率
85%置信度
0证据数
2024-09-11首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
启用了 TrustedHostMiddleware,但请求的 Host 头不在 allowed_hosts 列表中(在代理后或 localhost 上常见)。
English
TrustedHostMiddleware is enabled but the request Host header is not in the allowed_hosts list (common behind proxies or on localhost).
解决方案
-
93% 成功率
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', '*.example.com'])
-
87% 成功率
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware app.add_middleware(ProxyHeadersMiddleware, trusted_hosts='*')
无效尝试
常见但无效的做法:
-
85% 失败
Disables host header protection entirely.
-
80% 失败
Deployed environments still reject proxy hosts.