Search code examples
javaspringcloudgateway

How to add extra path to uri in spring cloud gatway


I want to add custom path for different apis in spring cloud gateway.

I have two apis:

  1. Service1: http://localhost:2121

service 1 has endpoint like: http://localhost:2121/abc

  1. Service2: http://localhost:3434

service 2 has endpoint like http://localhost:3434/abc

api gateway: http://localhost:8090

Problem:

I would like to add service1 path to API Gateway and I want to redirect to service 1

example 1: http://localhost:8090/service1/abc should redirect to http://localhost:2121/abc

example 2: http://localhost:8090/service1/anything should redirect to http://localhost:2121/anything

same things for service 2.

I use yml configuration for spring cloud gateway.

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: service1
          uri: http://localhost:2121
        - id: service2
          uri: http://localhost:3434

Thanks in advance.


Solution

  • spring:
        cloud:
            gateway:
                routes:
                -  id: service1
                   uri: http://localhost:2121
                   predicates:
                   -   Path=/service1/**
                   filters:
                   -   StripPrefix=1
                -  id: service2
                   uri: http://localhost:3434
                   predicates:
                   -   Path=/service2/**
                   filters:
                   -   StripPrefix=1
    

    then all requests mapping '/service1/xxxx' will proxy to service_1 '/xxxx'.

    spring cloud gateway reference will give you more details.