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_STRIP、AS_IN_REQUEST (預設) 和 ALWAYS_STRIP。
-
NEVER_STRIP:即使原始請求路徑不包含版本,版本也不會被剝離。 -
AS_IN_REQUEST:只有當原始請求路徑不包含版本時,版本才會被剝離。 -
ALWAYS_STRIP:版本總是被剝離,即使原始請求路徑包含版本。
hostValue 引數(如果提供)用於替換響應 Location 頭中的 host:port 部分。如果未提供,則使用 Host 請求頭的值。
protocolsRegex 引數必須是一個有效的正則表示式 String,協議名稱將根據它進行匹配。如果未匹配,則過濾器不執行任何操作。預設值為 http|https|ftp|ftps。