You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx基于主机名路由上游服务器的配置报错求助

Nginx基于主机名路由上游服务器的配置报错求助

你好,这个问题我之前也碰到过,核心原因是Nginx的upstream块是在配置加载阶段就会解析并初始化的,而你用到的$upstream_host是请求到达时才会赋值的变量——启动Nginx的时候,它根本不知道$upstream_host对应什么主机,自然会报“host not found”的错误。

想要实现你要的效果(不同域名对应“远程服务器+本地Unix Socket”的负载均衡池,且用ip_hash策略),可以按下面的方式调整配置:

解决方案:提前定义对应域名的上游池,用Map匹配路由

  1. 先为每个域名单独定义对应的upstream块,每个块里包含该域名对应的远程服务器和本地Socket:
# 对应api.example.to的上游池
upstream backend_api_example_to {
    ip_hash;
    server api2.example.to;
    server unix:/home/www/api.to/app.sock;
}

# 对应api.example2.to的上游池
upstream backend_api_example2_to {
    ip_hash;
    server api2.example2.to;
    server unix:/home/www/api.to/app.sock;
}

# 对应api.example3.to的上游池
upstream backend_api_example3_to {
    ip_hash;
    server api2.example3.to;
    server unix:/home/www/api.to/app.sock;
}

# 对应api.example4.to的上游池
upstream backend_api_example4_to {
    ip_hash;
    server api2.example4.to;
    server unix:/home/www/api.to/app.sock;
}
  1. 用map指令把请求的$host映射到对应的上游池名称:
map $host $target_upstream {
    api.example.to backend_api_example_to;
    api.example2.to backend_api_example2_to;
    api.example3.to backend_api_example3_to;
    api.example4.to backend_api_example4_to;
}
  1. 最后在Server块里,用变量指定上游池:
server {
    server_name api.example.to api.example2.to api.example3.to api.example4.to;

    # 其他配置(比如ssl、日志等)...

    location / {
        proxy_pass http://$target_upstream;
        # 其他proxy相关配置,比如proxy_set_header等...
    }
}

为什么这个方案可行?

因为每个upstream块都是在Nginx启动时就被解析初始化的,里面的服务器地址都是明确的,不会有“找不到主机”的问题;而map指令会在请求到达时,根据当前的$host动态选择对应的上游池,完美契合你的需求。

你的Ubuntu20.04上的Nginx 1.18或者1.22版本都完全支持这种配置方式,调整后重新加载Nginx配置(sudo nginx -s reload)就可以正常运行了。

备注:内容来源于stack exchange,提问作者nadermx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 15:37:46