请求里的 Host 头能信吗?Flask 3.1 的 TRUSTED_HOSTS 怎么用?SERVER_NAME 与它有什么区别?邮件里的链接该怎么生成?这篇用 test_client 与真实 gunicorn 把每种配置的结果逐个打印出来(防御向,只验证配置的效果)。
Host: example.com → 200 {'host': 'example.com', 'link': 'http://example.com/info'}
Host: other.test → 200 {'host': 'other.test', 'link': 'http://other.test/info'}
Host: example.com:8080 → 200 {'host': 'example.com:8080', 'link': 'http://example.com:8080/info'}
(任何 Host 都被接受;生成密码重置链接、邮件里的绝对地址如果直接用 request.host / url_for(_external=True),地址就由请求方决定) Host: 'example.com' → 200 {'host': 'example.com', 'link': 'http://example.com/info'}
Host: 'example.com:8080' → 200 {'host': 'example.com:8080', 'link': 'http://example.com:8080/info'}
Host: 'EXAMPLE.com' → 400 <!doctype html> <html lang=en> <title>400 Bad Request</title
Host: 'other.test' → 400 <!doctype html> <html lang=en> <title>400 Bad Request</title
Host: 'www.example.org' → 200 {'host': 'www.example.org', 'link': 'http://www.example.org/info'}
Host: 'example.org' → 200 {'host': 'example.org', 'link': 'http://example.org/info'}
Host: 'evil-example.com' → 400 <!doctype html> <html lang=en> <title>400 Bad Request</title
Host: '' → 400 <!doctype html> <html lang=en> <title>400 Bad Request</title SERVER_NAME=example.com,Host: example.com → 200 {'host': 'example.com', 'link': 'http://example.com/info'}
SERVER_NAME=example.com,Host: other.test → 200 {'host': 'other.test', 'link': 'http://example.com/info'}
请求之外(应用上下文里)url_for(_external=True): http://example.com/info Host: other.test → {'host_based': 'http://other.test/info', 'link': 'https://app.example.com/info'} 没有 ProxyFix Host: internal:8000, X-Forwarded-Host: public.example.com → {'host': 'internal:8000', 'link': 'http://internal:8000/info'}
ProxyFix(x_host=1) Host: internal:8000, X-Forwarded-Host: public.example.com → {'host': 'public.example.com', 'link': 'http://public.example.com/info'}
(只有前面确实有会覆盖这个头的可信代理时才应该启用;否则客户端自己就能伪造) Host: example.com → 200 {"host":"example.com"}
Host: other.test → 400 <!doctype html> <html lang=en> <title>400 Bad Request</title> <h1>Bad
Host: 127.0.0.1:9601 → 400 <!doctype html> <html lang=en> <title>400 Bad Request</title> <h1>Bad