This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Cloud Gateway 4.2.0!

RewriteLocationResponseHeader Filter

The RewriteLocationResponseHeader filter modifies the value of the Location response header, usually to get rid of backend-specific details. It takes the stripVersionMode, locationHeaderName, hostValue, and protocolsRegex parameters. The following listing configures a RewriteLocationResponseHeader filter:

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();
    }
}

For example, for a request of POST api.example.com/some/object/name, the Location response header value of object-service.prod.example.net/v2/some/object/id is rewritten as api.example.com/some/object/id.

The stripVersionMode parameter has the following possible values: NEVER_STRIP, AS_IN_REQUEST (default), and ALWAYS_STRIP.

  • NEVER_STRIP: The version is not stripped, even if the original request path contains no version.

  • AS_IN_REQUEST: The version is stripped only if the original request path contains no version.

  • ALWAYS_STRIP: The version is always stripped, even if the original request path contains version.

The hostValue parameter, if provided, is used to replace the host:port portion of the response Location header. If it is not provided, the value of the Host request header is used.

The protocolsRegex parameter must be a valid regex String, against which the protocol name is matched. If it is not matched, the filter does nothing. The default is http|https|ftp|ftps.