【Nginx】Nginx反向代理转发Host设置

#事故现场:

  服务器A(Nginx服务器):192.168.2.126

  服务器B(Web服务器):192.168.2.221

  服务器A反向代理服务器B,A配置了upstream为:

复制代码
http {
  upstream test_server {
    server 192.168.2.221:8080 weight=1 max_fails=3 fail_timeout=30s;
  }
}
复制代码

  用浏览器访问A:192.168.2.126 在服务端获取Host,结果为:test_server ,而我想得到的是:192.168.2.221

context.Request.Headers.Get("Host");// text_server
context.Request.ServerVariables["SERVER_NAME"]; // text_server

#原因及解决方案:

  默认情况下反向代理是不会转发请求中的Host头部,如果需要转发,则需要配置红色字体表示的选项参数。

复制代码
location /test {
            proxy_set_header  Host  $host;
            proxy_set_header  X-real-ip $remote_addr;
            proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;

            proxy_pass http://192.168.2.12:5252/test;
}
复制代码

#如果不修改Nginx配置,那服务端代码如何获取原始Host呢?

以asp.net代码为例:

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_HOST"];

#参考:https://www.cnblogs.com/yshyee/p/7531264.html

原文地址:https://www.cnblogs.com/Crazy-Liu/p/13030972.html