How to include the service's context-path when the gateway forwards requests
Springcloud Version: 2025.0.1 spring-cloud-starter-gateway-server-webflux: 4.3.3 nacos server: 3.0.3
Configuration as follows
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 cloud: gateway: server: webflux: discovery: locator: enabled: true lowerCaseServiceId: true # urlExpression: "'lb://' + serviceId + metadata['contextPath']"
Even if urlExpression is configured
Still unable to forward with context path
So how should I configure it ?
My idea is if there is any configuration where I can directly read the context path value in the metadata of the Nacos service registration information, so that I don't need to manually configure the routing
@yujunchengg, you can do this with discovery-locator filters; you do not need to configure each route manually.
url-expression sets the route’s destination URI, but a path appended to that URI is not prepended to the downstream request path. Keep the default lb://serviceId destination and customize the discovery locator’s RewritePath filter instead. Its arguments are SpEL expressions evaluated against the discovered ServiceInstance, including its metadata.
For Gateway 4.3.3, use:
spring:
cloud:
gateway:
server:
webflux:
discovery:
locator:
enabled: true
lower-case-service-id: true
filters:
- name: RewritePath
args:
regexp: "'/' + serviceId + '/?(?<remaining>.*)'"
replacement: "(metadata['contextPath'] ?: '') + '/$\\{remaining}'"
Remove your custom urlExpression. The default /serviceId/** path predicate remains unchanged. The filter above replaces the default discovery rewrite, preserving removal of the service ID while adding the context path.
For example, with service ID orders and metadata contextPath: /api:
Client request: /orders/items
Downstream request: /api/items
Important details:
- The Nacos discovery client must expose
contextPathinServiceInstance.getMetadata(). Configuring a context path in the downstream application alone does not guarantee that it is published as discovery metadata. - Use a value such as
/api: a leading slash and no trailing slash. For a service with no context path, omit the metadata key or use an empty string. The expression falls back to the normal service-ID stripping behavior. - Keep the same context-path metadata on all instances of a service. Discovery generates one route per service ID, not a separate rewrite for each load-balanced instance.
- Preserve the
\\in the double-quoted YAML replacement value; it produces the escaped replacement syntax used byRewritePath.
This behavior is supported by the 4.3.3 source: discovery filter expression evaluation and destination URI handling.
Validation: Checked the version-specific source and tested the Java regex replacement with and without a context path. This was not an end-to-end Nacos test. No GitHub comment was posted.