RewriteLocationResponseHeader 过滤器

RewriteLocationResponseHeader 过滤器修改 `Location` 响应头的值,通常用于去除后端特定的细节。它接收 `stripVersionMode`、`locationHeaderName`、`hostValue` 和 `protocolsRegex` 参数。以下清单配置了一个 `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 参数必须是一个有效的 regex String,协议名称将与它匹配。如果不匹配,则过滤器不执行任何操作。默认值为 http|https|ftp|ftps