该问题起源于一次将代码移植到微服务产生。当使用springcloud gateway更换掉nginx网关后,出现无法登录的情况,跟进发现转发的信息里丢失了Host
=== MimeHeaders ===
accept = */*
knife4j-gateway-code = ROOT
content-type = application/x-www-form-urlencoded
user-agent = Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36
request-origion = Knife4j
origin = http://localhost:7003
sec-fetch-site = same-origin
sec-fetch-mode = cors
sec-fetch-dest = empty
referer = http://localhost:7003/doc.html
accept-encoding = gzip, deflate, br
accept-language = zh-CN,zh;q=0.9
cookie = oxygentk=99d0a1b10bdd1443589a3416184d31984ed81136535c2e6498edbae12728f748; oxygenuid=36AB9A653683D50D4EC7E525BD9C96E9; charge-key={%22userId%22:3603%2C%22name%22:%22%E6%96%B0%E6%89%8B3603%E5%95%8A%22%2C%22icon%22:%22https://whalesing-web.oss-cn-guangzhou.aliyuncs.com/appres/forbidden.png%22}; AWX_RISK_ID=f6f3dd72e6cee7611eddf8328462756df97853ca; Hm_lvt_5819d05c0869771ff6e6a81cdec5b2e8=1684128760; Hm_lpvt_5819d05c0869771ff6e6a81cdec5b2e8=1684129236; lang=zh-CN; i_like_gogs=f529fa5db09e7bdd; JSESSIONID=20A183584BD3512F939D5696D56DA14A
forwarded = proto=http;host="localhost:7003";for="[0:0:0:0:0:0:0:1]:1926"
x-forwarded-for = 0:0:0:0:0:0:0:1
x-forwarded-proto = http
x-forwarded-prefix = /biz-core
x-forwarded-port = 7003
x-forwarded-host = localhost:7003
host = 192.168.1.196:8083
content-length = 0
上面看到host信息已经变成ip地址,而原地址被放到了x-forwarded-host。
因为request.getHeaders()会优先获得Host的Header,导致了request.getHeaders()的结果和原信息不一致。解决办法有两种
1)单独获得x-forwarded-for头部信息文章来源:https://www.toymoban.com/news/detail-725305.html
2)设置gateway按原头部进行转发。添加参数PreserveHostHeader:
bootstrap.yml文章来源地址https://www.toymoban.com/news/detail-725305.html
server:
port: 7003
spring:
application:
name: gateway
cloud:
nacos:
default-filters:
- PreserveHostHeader #发送原主机头
discovery:
namespace: public
server-addr: 192.168.1.196:8848
到了这里,关于springcloud gateway转发后getServerName被更改的问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!