StripPrefix configuration for spring cloud gateway

  springboot

Order

This paper mainly studies the stripPrefix configuration of spring cloud gateway.

Use zuul’s configuration

zuul:
  routes:
    demo:
      sensitiveHeaders: Access-Control-Allow-Origin,Access-Control-Allow-Methods    
      path: /demo/**
      stripPrefix: true
      url: http://demo.com.cn/

StripPrefix here defaults to true, that is, all /demo/xxxx requests are forwarded tohttp://demo.com.cn/xxxxTo remove the demo prefix

Configuration using spring cloud gateway

spring:
  cloud:
    gateway:
      default-filters:
      - AddResponseHeader=X-Response-Default-Foo, Default-Bar
      routes:
      - id: demo
        uri: http://demo.com.cn:80
        order: 8999 ## 越小越优先
        predicates: 
        - Path=/demo/**
        filters:
        - RewritePath=/demo/(?<segment>.*), /$\{segment}

Spring cloud gateway does not seem to have a ready-made stripPrefix configuration, but it can be implemented through rewritepath.

spring-cloud-gateway-core-2.0.0.M6-sources.jar! /org/springframework/cloud/gateway/filter/factory/RewritePathGatewayFilterFactory.java

public class RewritePathGatewayFilterFactory implements GatewayFilterFactory {

    public static final String REGEXP_KEY = "regexp";
    public static final String REPLACEMENT_KEY = "replacement";

    @Override
    public List<String> argNames() {
        return Arrays.asList(REGEXP_KEY, REPLACEMENT_KEY);
    }

    @Override
    public GatewayFilter apply(Tuple args) {
        final String regex = args.getString(REGEXP_KEY);
        String replacement = args.getString(REPLACEMENT_KEY).replace("$\\", "$");
        return apply(regex, replacement);
    }

    public GatewayFilter apply(String regex, String replacement) {
        return (exchange, chain) -> {
            ServerHttpRequest req = exchange.getRequest();
            addOriginalRequestUrl(exchange, req.getURI());
            String path = req.getURI().getPath();
            String newPath = path.replaceAll(regex, replacement);

            ServerHttpRequest request = mutate(req)
                    .path(newPath)
                    .build();

            exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());

            return chain.filter(exchange.mutate().request(request).build());
        };
    }
}

Replacing all (regex, replacement), here equivalent to regex is /demo/ (? < segment>.*), replacement is /${segment}

Summary

Spring cloud gateway can realize the effect of zuul’s stripPrefix with RewritePath and has more powerful functions.

doc