RewriteLocationResponseHeader 篩選器

RewriteLocationResponseHeader 篩選器會修改 Location 回應標頭的值,通常是為了移除後端特定的詳細資訊。它接受 stripVersionModelocationHeaderNamehostValueprotocolsRegex 參數。以下清單設定了 RewriteLocationResponseHeader 篩選器

application.yml
spring:
  cloud:
    gateway:
      mvc:
        routes:
        - id: rewritelocationresponseheader_route
          uri: http://example.org
          filters:
          - RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
GatewaySampleApplication.java
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();
    }
}

例如,對於 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