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

如何在Nginx中将Host设置为$upstream_addr

在Nginx中将Host设置为$upstream_addr的方法

要实现把请求的Host头设置为上游服务器地址的需求,你只需要在对应的location块里添加一行proxy_set_header Host $upstream_addr;就可以了。$upstream_addr是Nginx的内置变量,会自动获取当前请求被负载均衡到的上游节点的地址和端口(比如你的配置里的x.x.x.174:8001或x.x.x.96:8001)。

下面是补全并修改后的完整配置片段:

http {
    log_format my_upstream '$remote_addr [$time_local] "$request" $status'
                           '"$upstream_addr" $upstream_response_time $upstream_http_etag $host $http_host';
    access_log /var/log/nginx/upstream.log my_upstream;

    upstream myapp{
        ip_hash;
        server x.x.x.174:8001;
        server x.x.x.96:8001;
    }

    server {
        listen 9000;

        # websocket location /jms
        location /jms {
            proxy_pass http://myapp/jms;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            # 核心配置:将Host设置为上游服务器的地址
            proxy_set_header Host $upstream_addr;
            # 可选:添加常用的转发头,帮助上游识别真实客户端信息
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
}

几点关键说明:

  • 因为你用了ip_hash负载均衡策略,同一个客户端的请求会固定转发到某一个上游节点,对应的$upstream_addr也会保持一致,Host头不会频繁变化。
  • $upstream_addr只有在请求成功转发到上游后才会有值,所以必须确保你的proxy_pass指向的是upstream块(而不是单个服务器地址),这样变量才能正确获取到选中的节点信息。
  • 注意:部分上游应用可能依赖Host头做域名识别或路由,设置为$upstream_addr后,应用收到的Host会是自身的地址,请确认你的上游应用可以兼容这种方式,避免出现业务异常。

内容的提问来源于stack exchange,提问作者Bhaskar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:40:32