Skip to content

PreserveHostHeader GatewayFilter 工厂

PreserveHostHeader GatewayFilter 工厂没有参数。

此过滤器会设置一个请求属性,路由过滤器会检查该属性,以决定是发送原始的主机头 (Host header),还是发送由 HTTP 客户端确定的主机头。

以下示例配置了一个 PreserveHostHeader GatewayFilter:

application.yml

yaml
spring:
  cloud:
    gateway:
      routes:
      - id: preserve_host_route
        uri: https://example.org
        filters:
        - PreserveHostHeader

补充教学 —— 为什么要用 PreserveHostHeader?

默认行为: 当网关转发请求时,它通常会将 HTTP 请求头中的 Host 修改为目标 URI 的主机名。

  • 用户请求网关:curl -H "Host: www.gateway.com" http://gateway-ip/hello
  • 网关转发给下游 (https://example.org):网关会自动把 Host 头改成 example.org

为什么默认要改? 因为大多数 Web 服务器(如 Nginx, Tomcat)是基于 Host 头来决定把请求分发给哪个虚拟主机(Virtual Host)的。如果下游服务是 example.org,它期望收到的 Host 就是 example.org,否则它可能拒绝服务。

什么时候需要保留原 Host (PreserveHostHeader)?

  • 场景:下游服务需要知道客户端最初访问的域名是什么。
  • 例如:你正在做一个多租户系统(SaaS),下游服务根据用户访问的域名(如 tenant1.app.comtenant2.app.com)来决定加载哪个租户的数据库配置。
  • 配置后
    • 用户请求:Host: tenant1.app.com
    • 网关转发:Host: tenant1.app.com (保持不变)
    • 下游服务:收到了 tenant1.app.com,知道是租户1来了。

Based on Spring Framework.