Search code examples
regexspringspring-cloud-gateway

How to add a /api/v1/ prefix to uri in spring cloud gateway?


I have two services and a gateway working with eureka:
user-service running on 8081
health-service running on 8082
So far I tried this:

routes:
        - id: user-service-route
          uri: http://localhost:8081/user-service
          predicates:
            - Path=/user-service/**
          filters:
            - RewritePath=(?<serviceName>.*), /api/v1/{serviceName}

But it doesn't work.


Solution

  • Prefix location for all microservices if you use load balancer:

    server:
      port: 8765
    
    management:
      endpoints:
        web:
          exposure:
            include: gateway
    
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka
    
    spring:
      application:
        name: gateway
      cloud:
        gateway:
          discovery:
            locator:
              enabled: true
              lower-case-service-id: true
          default-filters:
            - RewritePath=/api/v1/.*?/(?<remaining>.*), /$\{remaining}
          routes:
            - predicates:
                - Path=/api/v1/profile/**
              uri: lb://profile
            - predicates:
                - Path=/api/v1/dictionary/**
              uri: lb://dictionary