## nginx配置反向代理不生效
2026年3月11日 00:47,值班的在群里甩了一句:api.xxx.com 的网关返回的是 index.html,下午新加的反向代理没起作用。机器 web01,Ubuntu 22.04。
root@web01:~# nginx -v
nginx version: nginx/1.24.0 (Ubuntu)
配置是当天下午另一个人写进 /etc/nginx/sites-enabled/api.conf 的。语法检查、reload 都是干净的。
root@web01:~# nginx -t
nginx: configuration file /etc/nginx/nginx.conf test is successful
root@web01:~# systemctl reload nginx
root@web01:~# echo $?
0
本机带着 Host 打过去:
root@web01:~# curl -svo /dev/null -H "Host: api.xxx.com" http://127.0.0.1/api/health
< HTTP/1.1 200 OK
< Server: nginx/1.24.0 (Ubuntu)
< Content-Type: text/html; charset=utf-8
200,但 Content-Type 是 text/html,返回的页面属于同机另一个站点。nginx -T 把实际生效的配置整段打出来,api.conf 那段确实在里面:
# configuration file /etc/nginx/sites-enabled/api.conf:
server {
listen 80;
server_name api.xxx.com;
location / {
proxy_pass http://10.20.3.17:8080;
}
}
先怀疑 8080 上的服务挂了,直连一下:
root@web01:~# curl -s http://10.20.3.17:8080/api/health
{"status":"UP","db":"ok","uptime":48213}
后端活着,响应体也对得上。
翻前端那边的调用代码,网关地址写的是 http://10.20.3.9:80/api。Host 头是 IP,不是 api.xxx.com。请求落到 000-default.conf 那个 listen 80 default_server 的块上了,api.conf 的 server_name 只有一个域名,IP 命不中,proxy_pass 根本没执行。
第一反应是给 api.conf 加 default_server。打开 000-default.conf 看了一眼,这台机器上还有另外三个域名指着它,改 listen 顺序等于把线上流量重排一遍,凌晨这么干不合适,手收回来了。
改成把 IP 补进 server_name:
server {
listen 80;
server_name api.xxx.com 10.20.3.9;
location / {
proxy_pass http://10.20.3.17:8080;
}
}
reload 后再打:
root@web01:~# curl -svo /dev/null http://10.20.3.9/api/health
< HTTP/1.1 200 OK
< Content-Type: application/json
{"status":"UP","db":"ok"}
01:12 前端确认页面正常了。后来在内网 API 网关的接入说明里加了一条:调用地址一律写域名,不要写机器 IP。
nginx proxy_pass 文档:https://nginx.org/en/docs/http/ngx_http_proxy_module.html

评论(0)