Nginx 请求转发到 Gateway 网关的一个坑

原因就是 Nginx 转发到网关时会把请求头 Host 丢掉。
在 Nginx 中添加 proxy_set_header Host $host; 即可。

1、修改“C:\Windows\System32\drivers\etc\hosts”,添加192.168.56.10 gulimall.com。关闭防火墙

2、修改nginx/conf/nginx.conf,将upstream映射到我们的网关服务

1
2
3
4
upstream gulimall{
# 88是网关
server 192.168.56.1:88;
}

3、修改nginx/conf/conf.d/gulimall.conf,接收到gulimall.com的访问后,如果是/,转交给指定的upstream,由于nginx的转发会丢失host头,造成网关不知道原host,所以我们添加头信息

1
2
3
4
location / {
proxy_pass http://gulimall;
proxy_set_header Host $host;
}

4、配置gateway为服务器,将域名为**.gulimall.com转发至商品服务。配置的时候注意 网关优先匹配的原则,所以要把这个配置放到后面

1
2
3
4
- id: gulimall_host_route
uri: lb://gulimall-product
predicates:
- Host=**.gulimall.com

测试:http://gulimall.com/api/product/attrgroup/list/1

http://localhost:88/api/product/attrgroup/list/1

请求结果相同

此时请求接口和请求页面都是gulimall.com