Nginx server块中不能直接配置健康检查探针页面,需通过location代理后端健康接口;须禁用缓存、设置短超时、确保路径透传与Host头正确,并在upstream中启用check指令配合HTTP探测。

在 Nginx 的 Virtual Host(即 server 块)中,**不能直接配置健康检查探针页面本身**——探针目标(如 /health)是后端应用提供的,Nginx 作为负载均衡器只负责探测它;但你可以通过 location 配置一个专用于暴露或代理该探针的路径,并确保它被正确转发、不被缓存、不触发重写,从而稳定响应负载均衡器的探测请求。
为后端健康接口配置专用代理 location
这是最常用且可靠的做法:在 server 块内定义一个 location,将探测请求精准转发到上游服务的健康端点,避免路径错位或 header 干扰。
- 使用
proxy_pass指向后端具体地址(不带 URI),再用rewrite或proxy_set_header确保原始路径透传 - 禁用缓存和重定向干扰:
proxy_cache_bypass 1、proxy_no_cache 1、proxy_redirect off - 设置超时与失败重试,匹配健康检查逻辑:
proxy_connect_timeout 1s、proxy_read_timeout 2s
示例:
location /health {
proxy_pass http://app_backend;
proxy_http_version 1.1;
proxy_set_header Connection '';
proxy_cache_bypass 1;
proxy_no_cache 1;
proxy_connect_timeout 1;
proxy_read_timeout 2;
proxy_send_timeout 2;
}
确保 upstream 中启用对应主动探测路径
健康检查是否生效,关键在 upstream 块。Virtual Host 里的 location 只是“入口”,真正发起探测的是 upstream 内部的 check 指令(需 nginx_upstream_check_module)。
-
check_http_send必须明确指定 HTTP 方法与路径,例如:"GET /health HTTP/1.1\r\nHost: $host\r\n\r\n" -
check_http_expect_alive应严格限定成功码,如http_2xx,避免把 404 或 503 当健康 - 若后端健康接口返回 JSON(如
{"status":"UP"}),可配合check_http_expect_alive+ 正则匹配 body(需模块支持)
避免 location 冲突与路径截断
常见错误是 location 匹配过于宽泛(如 location / { ... })导致 /health 被通用规则处理,丢失 Host 头或被重写。
- 把
/health放在通用location /之前,保证优先匹配 - 不要在该 location 中使用
rewrite修改 URI,除非你明确控制后端接收路径 - 若后端要求 Host 头为特定值(如
health.example.com),用proxy_set_header Host health.example.com
验证探针可达性与响应一致性
部署后务必手动测试:用 curl 模拟探测请求,确认返回状态码、body 和响应时间符合预期。
- 执行:
curl -I http://your-nginx-domain/health,检查是否返回 200 - 对比直接访问后端(如
curl http://192.168.1.10:8080/health),确保内容一致 - 查看 Nginx error log,确认无
upstream timed out或connection refused


















