nginx代理给网关时 丢失请求的host信息问题

nginx搭建域名访问环境

描述:访问gulimall.com,Nginx反向代理到网关地址,然后网关转发到具体的product服务

域名映射的效果如下:

具体步骤:

(1)hosts文件配置域名和ip映射

修改windows下host文件:C:\Windows\System32\drivers\etc\hosts

为了方便,可以使用SwitchHost工具

(2)配置nginx.conf

在http块中,配置上游服务器

vi /mydata/nginx/conf/nginx.conf

upstream gulimall{        #配置上游服务器,起名为gulimall
    server 192.168.56.1:88;   #配置上游服务器为网关地址,192.168.56.1为windows的ip地址
  }
(3)配置gulimall.conf

vi /etc/nginx/conf.d/gulimall.conf

在server块中配置请求的路由

location / {    #配置请求的路由
      proxy_pass http://gulimall;   #因为主配置文件配置了上游服务器为网关地址,所以可以请求路由到http://192.168.xxx.xxx:10000/
  }
(4)重启nginx

(5)配置网关

添加路由规则

- id: gulimall_host_route
uri: lb://gulimall-product
predicates:
- Host=**.gulimall.com,gulimall.com
(6)测试

访问gulimall.com报404,丢失请求的host信息

问题:是nginx代理给网关时 丢失请求的host信息

解决:proxy_set_header Host $host

在gulimall.conf 设置 proxy_set_header Host $host

location / {    #配置请求的路由
      proxy_set_header Host $host;   #坑点:Nginx代理给网关时会丢失请求的host等信息
      proxy_pass http://gulimall;   #因为主配置文件配置了上游服务器为网关地址,所以可以请求路由到http://192.168.xxx.xxx:10000/
  }

问题即可解决!

posted @ 2023-05-27 15:21  小謝同學  阅读(349)  评论(0编辑  收藏  举报