跳到主要内容

RewriteLocationResponseHeader 过滤器

DeepSeek V3 中英对照 RewriteLocationResponseHeader Filter RewriteLocationResponseHeader Filter

RewriteLocationResponseHeader 过滤器用于修改 Location 响应头的值,通常是为了去除与后端相关的细节。它接受 stripVersionModelocationHeaderNamehostValueprotocolsRegex 参数。以下代码片段配置了一个 RewriteLocationResponseHeader 过滤器:

spring:
cloud:
gateway:
mvc:
routes:
- id: rewritelocationresponseheader_route
uri: http://example.org
filters:
- RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
yaml
import static org.springframework.cloud.gateway.server.mvc.filter.AfterFilterFunctions.addResponseHeader;
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("https://example.org"))
.after(rewriteLocationResponseHeader(config -> config.setLocationHeaderName("Location").setStripVersion(StripVersion.AS_IN_REQUEST)))
.build();
}
}
java

例如,对于一个请求 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_STRIPAS_IN_REQUEST(默认值)和 ALWAYS_STRIP

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

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

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

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

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