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
引數必須是一個有效的 regex String
,協議名稱將與它匹配。如果不匹配,則過濾器不執行任何操作。預設值為 http|https|ftp|ftps
。