Rewrite paths with the konghq.com/rewrite annotation

Related Documentation
Related Resources
TL;DR

Use the konghq.com/rewrite annotation to specify the new upstream path, for example konghq.com/rewrite=/users/$1.

Prerequisites

If you don’t have a Konnect account, you can get started quickly with our onboarding wizard.

  1. The following Konnect items are required to complete this tutorial:
    • Personal access token (PAT): Create a new personal access token by opening the Konnect PAT page and selecting Generate Token.
  2. Set the personal access token as an environment variable:

    export KONNECT_TOKEN='YOUR KONNECT TOKEN'
    

Use the Konnect API to create a new CLUSTER_TYPE_K8S_INGRESS_CONTROLLER Control Plane:

CONTROL_PLANE_DETAILS=$(curl -X POST "https://us.api.konghq.com/v2/control-planes" \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "My KIC CP",
       "cluster_type": "CLUSTER_TYPE_K8S_INGRESS_CONTROLLER"
     }')

We’ll need the id and telemetry_endpoint for the values.yaml file later. Save them as environment variables:

CONTROL_PLANE_ID=$(echo $CONTROL_PLANE_DETAILS | jq -r .id)
CONTROL_PLANE_TELEMETRY=$(echo $CONTROL_PLANE_DETAILS | jq -r '.config.telemetry_endpoint | sub("https://";"")')

Create mTLS certificates

Kong Ingress Controller talks to Konnect over a connected secured with TLS certificates.

Generate a new certificate using openssl:

openssl req -new -x509 -nodes -newkey rsa:2048 -subj "/CN=kongdp/C=US" -keyout ./tls.key -out ./tls.crt

The certificate needs to be a single line string to send it to the Konnect API with curl. Use awk to format the certificate:

export CERT=$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' tls.crt);

Next, upload the certificate to Konnect:

curl -X POST "https://us.api.konghq.com/v2/control-planes/$CONTROL_PLANE_ID/dp-client-certificates" \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "cert": "'$CERT'"
     }'

Finally, store the certificate in a Kubernetes secret so that Kong Ingress Controller can read it:

kubectl create namespace kong -o yaml --dry-run=client | kubectl apply -f -
kubectl create secret tls konnect-client-tls -n kong --cert=./tls.crt --key=./tls.key
  1. Add the Kong Helm charts:

    helm repo add kong https://charts.konghq.com
    helm repo update
    
  2. Install Kong Ingress Controller using Helm:

    helm install kong kong/ingress -n kong --create-namespace --set controller.ingressController.env.feature_gates="RewriteURIs=true"
    
  3. Set $PROXY_IP as an environment variable for future commands:

    export PROXY_IP=$(kubectl get svc --namespace kong kong-gateway-proxy -o jsonpath='{range .status.loadBalancer.ingress[0]}{@.ip}{@.hostname}{end}')
    echo $PROXY_IP
    

This how-to requires some Kubernetes services to be available in your cluster. These services will be used by the resources created in this how-to.

kubectl apply -f https://developer.konghq.com/manifests/kic/httpbin-service.yaml -n kong

Configure a rewrite

This feature requires the RewriteURIs feature gate to be activated and only works with Ingress resources. If you installed Kong Ingress Controller using the Helm command in the prerequisites, you should already have this feature gate enabled.

Kong Ingress Controller provides the konghq.com/rewrite annotation to customize the request path before it is sent to the upstream service.

The annotation can be used on Ingress and HTTPRoute resources, and configures a request-transformer plugin within Kong Gateway when added to a Route.

The following definition creates a Route that matches the path /external-path/(\w+) and rewrites it to /anything/$1 before sending the request upstream:

Alternatively, you can define this in a plugin configuration:

echo "
apiVersion: configuration.konghq.com/v1
kind: KongClusterPlugin
metadata:
  name: request-transformer
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
  labels:
    global: 'true'
config:
  replace:
    uri: '/anything/$(uri_captures[1])'
plugin: request-transformer
" | kubectl apply -f -

The $1 in the annotation is expanded to $(uri_captures[1]) in the plugin configuration.

Up to nine capture groups are supported using the konghq.com/rewrite annotation. If you need more than 9 capture groups, create a KongPlugin resource to handle the transformation.

Validate your configuration

To validate that your rewrite is working, make an HTTP request to /external-path/123:

curl "$PROXY_IP/external-path/123"
curl "$PROXY_IP/external-path/123"

The response contains a url key which shows the URL sent to the upstream service, plus an X-Forwarded-Path header that shows the original request path.

Cleanup

kubectl delete -n kong -f https://developer.konghq.com/manifests/kic/httpbin-service.yaml
helm uninstall kong -n kong
Something wrong?

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!