RewriteLocationResponseHeader 过滤器

RewriteLocationResponseHeader 过滤器修改 Location 响应头的值,通常是为了去除后端特定的细节。它接收 stripVersionModelocationHeaderNamehostValueprotocolsRegex 参数。以下列表配置了一个 RewriteLocationResponseHeader 过滤器

application.yml
spring:
  cloud:
    gateway:
      mvc:
        routes:
        - id: rewritelocationresponseheader_route
          uri: http://example.org
          predicates:
          - Path=/**
          filters:
          - RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.filter.RewriteLocationResponseHeaderFilterFunctions.rewriteLocationResponseHeader;
import static org.springframework.cloud.gateway.server.mvc.filter.RewriteLocationResponseHeaderFilterFunctions.StripVersion;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsRewriteLocationResponseHeader() {
        return route("rewritelocationresponseheader_route")
            .GET("/**", http())
            .before(uri("https://example.org"))
            .after(rewriteLocationResponseHeader(config -> config.setLocationHeaderName("Location")
                    .setStripVersion(StripVersion.AS_IN_REQUEST)))
            .build();
    }
}

例如,对于 POST api.example.com/some/object/name 的请求,Location 响应头的值 object-service.prod.example.net/v2/some/object/id 被重写为 api.example.com/some/object/id

stripVersionMode 参数可能的值有:NEVER_STRIPAS_IN_REQUEST (默认) 和 ALWAYS_STRIP

  • NEVER_STRIP:即使原始请求路径不包含版本,版本也不会被剥离。

  • AS_IN_REQUEST:只有当原始请求路径不包含版本时,版本才会被剥离。

  • ALWAYS_STRIP:版本总是被剥离,即使原始请求路径包含版本。

hostValue 参数(如果提供)用于替换响应 Location 头中的 host:port 部分。如果未提供,则使用 Host 请求头的值。

protocolsRegex 参数必须是一个有效的正则表达式 String,协议名称将根据它进行匹配。如果未匹配,则过滤器不执行任何操作。默认值为 http|https|ftp|ftps

© . This site is unofficial and not affiliated with VMware.