Rewrite dynamic path segments
Use the with() and regexReplace() CEL functions together with request.path to rewrite dynamic path segments before forwarding the request to the upstream.
with() binds a complex expression to a temporary variable to avoid evaluating it multiple times. regexReplace() replaces text matching a regular expression with a replacement string. Together, they are useful for sanitizing dynamic values such as replacing numeric IDs in a path with a placeholder before the request reaches the upstream service.
Before you begin
- Set up an agentgateway proxy.
- Install the httpbin sample app.
Rewrite dynamic path segments
In this example, you bind request.path to a temporary variable using with(), then use regexReplace() to replace any numeric path segments with id. Setting the result on the :path pseudo header rewrites the actual request that is path forwarded to the upstream service.
For example, a request to /users/12345 is forwarded upstream as /users/id.
Create an AgentgatewayPolicy resource with your transformation rules.
kubectl apply -f- <<EOF apiVersion: agentgateway.dev/v1alpha1 kind: AgentgatewayPolicy metadata: name: transformation namespace: httpbin spec: targetRefs: - group: gateway.networking.k8s.io kind: HTTPRoute name: httpbin traffic: transformation: request: set: - name: :path value: 'request.path.with(p, p.regexReplace("/[0-9]+", "/id"))' EOFSend a request to the httpbin app using a path with a numeric ID. Verify that you get back a 200 HTTP response code and that the
urlfield in the response body shows the normalized path forwarded to the upstream.curl -vi http://$INGRESS_GW_ADDRESS:80/anything/users/12345 \ -H "host: www.example.com:80"curl -vi localhost:8080/anything/users/12345 \ -H "host: www.example.com"Example output:
< HTTP/1.1 200 OK HTTP/1.1 200 OK ... { "args": {}, "headers": { "Accept": [ "*/*" ], "Host": [ "www.example.com" ], "User-Agent": [ "curl/8.7.1" ] }, "origin": "10.244.0.6:12345", "url": "http://www.example.com/anything/users/id" }
Cleanup
You can remove the resources that you created in this guide.kubectl delete AgentgatewayPolicy transformation -n httpbin