跳到主要内容
版本:5.0.1

RewriteLocationResponseHeader 过滤器

DeepSeek V3 中英对照 RewriteLocationResponseHeader Filter RewriteLocationResponseHeader Filter

RewriteLocationResponseHeader 过滤器用于修改 Location 响应头的值,通常用于移除后端特定的细节信息。它接受 stripVersionMode、locationHeaderName、hostValue 和 protocolsRegex 参数。以下清单配置了一个 RewriteLocationResponseHeader 过滤器:

spring:
cloud:
gateway:
server:
webmvc:
routes:
- id: rewritelocationresponseheader_route
uri: http://example.org
predicates:
- Path=/**
filters:
- RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
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](https://api.example.com/some/object/name) 的请求,Location 响应头值 [object-service.prod.example.net/v2/some/object/id](https://object-service.prod.example.net/v2/some/object/id) 会被重写为 [api.example.com/some/object/id](https://api.example.com/some/object/id)。

stripVersionMode 参数有以下可能的值:NEVER_STRIP、AS_IN_REQUEST(默认值)和 ALWAYS_STRIP。

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

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

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

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

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