Skip to content
Hands-on IT IT Drills

Day 3: Filters – Redirect, Rewrite, Headers, Mirroring, Timeouts

Goal: You replace the typical Ingress annotations with filters and rule fields of the HTTPRoute. · Duration: approx. 60 min · Prerequisite: Day 2

Briefing

  • Filters are attached to a rule (rules[].filters) and modify the request or response before or after the backend responds.
  • Core (every implementation): RequestHeaderModifier, RequestRedirect. Extended: ResponseHeaderModifier, URLRewrite, RequestMirror, CORS.
  • RequestRedirect answers the request itself – a rule with a redirect needs no backendRefs.
  • Timeouts are not in filters, but directly on the rule (timeouts, Standard). retry is still experimental in v1.6.
  • Envoy Gateway can do all of this – what another implementation can do is listed in its conformance report.
ingress-nginx annotation Gateway API
permanent-redirect, ssl-redirect Filter RequestRedirect
rewrite-target, upstream-vhost Filter URLRewrite
configuration-snippet (headers) RequestHeaderModifier / ResponseHeaderModifier
mirror-target Filter RequestMirror
proxy-read-timeout rules[].timeouts
enable-cors Filter CORS

Drill 1: Path Redirects

cd ~/gw-lab/tag03
export GW_IP=$(gw-ip.sh)
cat > redirect.yaml <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop-redirects
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
  hostnames:
    - shop.gw.localtest.me
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /alt
      filters:
        - type: RequestRedirect
          requestRedirect:
            path:
              type: ReplacePrefixMatch
              replacePrefixMatch: /neu
            statusCode: 301
    - matches:
        - path:
            type: Exact
            value: /kasse
      filters:
        - type: RequestRedirect
          requestRedirect:
            path:
              type: ReplaceFullPath
              replaceFullPath: /checkout
            statusCode: 302
EOF
kubectl apply -f redirect.yaml
r() { curl -si --resolve shop.gw.localtest.me:80:$GW_IP "$@" \
  | grep -iE '^(HTTP|location)'; }
r 'http://shop.gw.localtest.me/alt/produkt/42?farbe=rot'
r 'http://shop.gw.localtest.me/altwaren'
r 'http://shop.gw.localtest.me/kasse'

Expected:

httproute.gateway.networking.k8s.io/shop-redirects created
HTTP/1.1 301 Moved Permanently
location: http://shop.gw.localtest.me/neu/produkt/42?farbe=rot
HTTP/1.1 200 OK
HTTP/1.1 302 Found
location: http://shop.gw.localtest.me/checkout

ReplacePrefixMatch only swaps the matched prefix and keeps the rest and the query. ReplaceFullPath replaces the whole path. /altwaren does not match /alt (segments, Day 2) and lands at shop-v1 via the route shop. The two routes shop and shop-redirects share the hostname – that way a team can maintain redirects separately.

Save your progress? Sign up for free

Drill 2: Hostname Redirect www → shop

cat > www.yaml <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: www
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
  hostnames:
    - www.gw.localtest.me
  rules:
    - filters:
        - type: RequestRedirect
          requestRedirect:
            hostname: shop.gw.localtest.me
            statusCode: 301
EOF
kubectl apply -f www.yaml
curl -si --resolve www.gw.localtest.me:80:$GW_IP \
  'http://www.gw.localtest.me/kasse?x=1' | grep -iE '^(HTTP|location)'

Expected:

httproute.gateway.networking.k8s.io/www created
HTTP/1.1 301 Moved Permanently
location: http://shop.gw.localtest.me/kasse?x=1

The rule has neither matches nor backendRefs: everything for www is redirected, path and query stay. Other fields of requestRedirect are scheme and port – you build the HTTP→HTTPS redirect on Day 4.

Save your progress? Sign up for free

Drill 3: URL Rewrite Instead of rewrite-target

The API team publishes shop-v2 under api.gw.localtest.me/api/v2, but the service itself only knows /. The route already contains the header filters for Drill 4.

cat > api.yaml <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: api
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
  hostnames:
    - api.gw.localtest.me
  rules:
    - name: v2
      matches:
        - path:
            type: PathPrefix
            value: /api/v2
      filters:
        - type: URLRewrite
          urlRewrite:
            hostname: shop-v2.intern
            path:
              type: ReplacePrefixMatch
              replacePrefixMatch: /
        - type: RequestHeaderModifier
          requestHeaderModifier:
            set:
              - name: x-team
                value: shop
            add:
              - name: x-via
                value: gw-lab
            remove:
              - user-agent
        - type: ResponseHeaderModifier
          responseHeaderModifier:
            add:
              - name: x-served-by
                value: shop-v2
            remove:
              - x-content-type-options
      backendRefs:
        - name: shop-v2
          port: 80
EOF
kubectl apply -f api.yaml
a() { curl -s --resolve api.gw.localtest.me:80:$GW_IP "$@"; }
a 'http://api.gw.localtest.me/api/v2/produkte?seite=2' \
  | jq -c '{path, host, fwd: .headers["X-Forwarded-Host"], service}'
a http://api.gw.localtest.me/api/v2 | jq -c '{path}'
a -o /dev/null -w '%{http_code}\n' http://api.gw.localtest.me/api/v1/x

Expected:

httproute.gateway.networking.k8s.io/api created
{"path":"/produkte?seite=2","host":"shop-v2.intern","fwd":["api.gw.localtest.me"],…}
{"path":"/"}
404

The backend sees the path /produkte and the host shop-v2.intern; Envoy reports the original host in X-Forwarded-Host. Unlike rewrite-target with regex groups, ReplacePrefixMatch is portable and only allowed together with a PathPrefix match.

Redirect and rewrite are mutually exclusive in one rule – the CRD validation rejects this right at apply time:

cat <<'EOF' | kubectl apply -f -
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: verboten
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
  rules:
    - filters:
        - type: RequestRedirect
          requestRedirect:
            scheme: https
        - type: URLRewrite
          urlRewrite:
            hostname: x.intern
EOF

Expected:

The HTTPRoute "verboten" is invalid: spec.rules[0].filters: Invalid value: May specify
either httpRouteFilterRequestRedirect or httpRouteFilterRequestRewrite, but not both

Save your progress? Sign up for free

Drill 4: Set, Add and Remove Headers

Besides the rewrite, the rule v2 in api.yaml carries two header filters: RequestHeaderModifier with set, add and remove, plus a ResponseHeaderModifier.

a -H 'x-team: hacker' -H 'x-via: client' http://api.gw.localtest.me/api/v2/ \
  | jq -c '.headers | {"X-Team", "X-Via", "User-Agent"}'
a -si http://api.gw.localtest.me/api/v2/ | grep -iE '^(HTTP|content-type|x-)'

Expected:

{"X-Team":["shop"],"X-Via":["client","gw-lab"],"User-Agent":null}
HTTP/1.1 200 OK
content-type: application/json
x-served-by: shop-v2
Action Effect
set overwrites an existing value (hacker → shop)
add appends (client stays, gw-lab is added)
remove removes the header entirely

On the response side, x-content-type-options: nosniff is missing, which the echo server otherwise always sends.

Security: set on identity headers like x-team or x-user is mandatory if backends trust them. With add, a client could send the value itself.

Save your progress? Sign up for free

Drill 5: Request Mirroring

Test a new version under real load without customers seeing its responses: 50% of the requests to shop additionally go to shop-v2 as a copy.

cat > mirror.yaml <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
      sectionName: http
  hostnames:
    - shop.gw.localtest.me
  rules:
    - filters:
        - type: RequestMirror
          requestMirror:
            backendRef:
              name: shop-v2
              port: 80
            percent: 50
      backendRefs:
        - name: shop-v1
          port: 80
EOF
kubectl apply -f mirror.yaml
for i in $(seq 1 20); do
  curl -s --resolve shop.gw.localtest.me:80:$GW_IP \
    "http://shop.gw.localtest.me/spiegel-$i" | jq -r .service
done | sort | uniq -c
kubectl -n shop logs deploy/shop-v2 --since=60s | grep -c spiegel

Expected (the second number fluctuates around 10):

httproute.gateway.networking.k8s.io/shop configured
  20 shop-v1
8

All responses come from shop-v1. The copies to shop-v2 are “fire and forget”: Envoy does not wait for them and discards their responses. Instead of percent you can also use fraction (e.g. 1 in 1000).

Warning: Mirrored requests trigger real side effects. POSTs to an order endpoint would place orders twice – use mirroring only for idempotent paths or with a backend that lets write operations go nowhere.

kubectl apply -f ~/gw-lab/code/demo/route-shop.yaml

Expected:

httproute.gateway.networking.k8s.io/shop configured

Save your progress? Sign up for free

Drill 6: Timeouts

cat > resilienz.yaml <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: resilienz
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
  hostnames:
    - api.gw.localtest.me
  rules:
    - name: langsam
      matches:
        - path:
            type: PathPrefix
            value: /langsam
      timeouts:
        request: 2s
      backendRefs:
        - name: shop-v1
          port: 80
EOF
kubectl apply -f resilienz.yaml
a -o /dev/null -w '%{http_code} %{time_total}s\n' \
  'http://api.gw.localtest.me/langsam?delay=1s'
a -si -w '\n%{time_total}s\n' 'http://api.gw.localtest.me/langsam?delay=3s' \
  | grep -E '^HTTP|upstream|s$'

Expected:

httproute.gateway.networking.k8s.io/resilienz created
200 1.006343s
HTTP/1.1 504 Gateway Timeout
upstream request timeout
2.003160s

timeouts.request limits the time until Envoy answers the client – including all retries. timeouts.backendRequest applies per individual attempt to the backend and must not be greater than request. The route resilienz shares api.gw.localtest.me with the route api.

Save your progress? Sign up for free

Drill 7: Retries (Experimental)

retry is only available in the Experimental channel – which the Envoy Gateway chart installed (Day 1). Append a second rule to resilienz.yaml:

cat >> resilienz.yaml <<'EOF'
    - name: wackelig
      matches:
        - path:
            type: PathPrefix
            value: /retry
      retry:
        codes: [503]
        attempts: 3
        backoff: 100ms
      backendRefs:
        - name: shop-v1
          port: 80
EOF
kubectl apply -f resilienz.yaml
for n in 2 3 4; do
  printf 'succeedAfter=%s -> ' "$n"
  a -o /dev/null -w '%{http_code}\n' \
    "http://api.gw.localtest.me/retry/?uuid=r$n&succeedAfter=$n&responseCode=503"
done

Expected:

httproute.gateway.networking.k8s.io/resilienz configured
succeedAfter=2 -> 200
succeedAfter=3 -> 200
succeedAfter=4 -> 503

For each uuid, the echo server fails exactly succeedAfter times with 503. attempts: 3 means three retries – so up to four attempts. After four failures, Envoy passes the last 503 on to the client.

Tip: If you are only allowed to install Standard CRDs, you get retries, circuit breakers and rate limits via Envoy Gateway’s BackendTrafficPolicy (Day 10).

Save your progress? Sign up for free

Drill 8: CORS as a Filter

Since Gateway API v1.5, CORS is a Standard filter – no annotation, no policy needed.

cat > cors.yaml <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: cors
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
  hostnames:
    - api.gw.localtest.me
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /public
      filters:
        - type: CORS
          cors:
            allowOrigins:
              - https://shop.gw.localtest.me
            allowMethods: [GET, POST]
            allowHeaders: [content-type]
            maxAge: 600
      backendRefs:
        - name: shop-v1
          port: 80
EOF
kubectl apply -f cors.yaml
pre() { a -si -X OPTIONS http://api.gw.localtest.me/public/x \
  -H "Origin: $1" -H 'Access-Control-Request-Method: POST' \
  | grep -iE '^(HTTP|access-control)'; }
pre https://shop.gw.localtest.me
echo ---
pre https://evil.example

Expected:

httproute.gateway.networking.k8s.io/cors created
HTTP/1.1 200 OK
access-control-allow-origin: https://shop.gw.localtest.me
access-control-allow-methods: GET, POST
access-control-allow-headers: content-type
access-control-max-age: 600
---
HTTP/1.1 200 OK
access-control-allow-methods: GET, POST
access-control-allow-headers: content-type
access-control-max-age: 600

Envoy answers the preflight itself. For the foreign origin, access-control-allow-origin is missing – the browser blocks the actual request.

Save your progress? Sign up for free

Checkpoint

check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
GW_IP=$(gw-ip.sh)
S="shop.gw.localtest.me:80:$GW_IP"; A="api.gw.localtest.me:80:$GW_IP"
check "Prefix-Redirect /alt -> /neu" \
  'curl -si --resolve "$S" http://shop.gw.localtest.me/alt/x \
     | grep -qi "location:.*/neu/x"'
check "Rewrite /api/v2 -> /" \
  '[ "$(curl -s --resolve "$A" http://api.gw.localtest.me/api/v2 | jq -r .path)" = / ]'
check "Response-Header x-served-by" \
  'curl -si --resolve "$A" http://api.gw.localtest.me/api/v2/ | grep -qi "^x-served-by"'
check "Timeout liefert 504" \
  '[ "$(curl -s -o /dev/null -w "%{http_code}" --resolve "$A" \
     "http://api.gw.localtest.me/langsam?delay=3s")" = 504 ]'
U="http://api.gw.localtest.me/retry/?uuid=k$RANDOM&succeedAfter=2&responseCode=503"
check "Retry rettet 2 Fehlschläge" \
  '[ "$(curl -s -o /dev/null -w "%{http_code}" --resolve "$A" "$U")" = 200 ]'
check "Route shop wieder ohne Mirror" \
  '! kubectl -n shop get httproute shop -o yaml | grep -q RequestMirror'

Expected:

✔ Prefix-Redirect /alt -> /neu
✔ Rewrite /api/v2 -> /
✔ Response-Header x-served-by
✔ Timeout liefert 504
✔ Retry rettet 2 Fehlschläge
✔ Route shop wieder ohne Mirror

Challenge

Old clients still call api.gw.localtest.me/legacy/.... Forward them to shop-v1 without the prefix, mark every response with the header deprecation: true and abort after 1 s. Clean up all of today’s practice routes afterwards.

Hint: Rewrite, response header and timeout fit into a single rule.

Solution

cat > ~/gw-lab/tag03/legacy.yaml <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: legacy
  namespace: shop
spec:
  parentRefs:
    - name: web
      namespace: infra
  hostnames:
    - api.gw.localtest.me
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /legacy
      filters:
        - type: URLRewrite
          urlRewrite:
            path:
              type: ReplacePrefixMatch
              replacePrefixMatch: /
        - type: ResponseHeaderModifier
          responseHeaderModifier:
            set:
              - name: deprecation
                value: "true"
      timeouts:
        request: 1s
      backendRefs:
        - name: shop-v1
          port: 80
EOF
kubectl apply -f ~/gw-lab/tag03/legacy.yaml
a -si 'http://api.gw.localtest.me/legacy/bestellung/7' | grep -iE '^(HTTP|deprecation)'
a 'http://api.gw.localtest.me/legacy/bestellung/7' | jq -r '.path + " " + .service'
a -o /dev/null -w '%{http_code}\n' 'http://api.gw.localtest.me/legacy/x?delay=2s'
kubectl -n shop delete httproute shop-redirects www api resilienz cors legacy

Expected:

httproute.gateway.networking.k8s.io/legacy created
HTTP/1.1 200 OK
deprecation: true
/bestellung/7 shop-v1
504
httproute.gateway.networking.k8s.io "shop-redirects" deleted from shop namespace
...
httproute.gateway.networking.k8s.io "legacy" deleted from shop namespace

Only the route shop remains – the state of code/demo that Day 4 builds on.

Save your progress? Sign up for free

Enterprise Note

  • Check the conformance report before switching implementations: not every implementation has to support Extended filters like RequestMirror or CORS.
  • Always set timeouts explicitly. Envoy defaults (15 s route timeout) rarely fit batch endpoints or streaming.
  • Retries only for idempotent requests and with a budget – otherwise they amplify load spikes. In Envoy Gateway: BackendTrafficPolicy with retry and circuit breaker (Day 10).
  • Header filters are not a security boundary: authentication belongs in a SecurityPolicy (JWT/OIDC, Day 10), not in home-grown header conventions.
  • Mirroring in production requires its own capacity planning: the target gets up to 100% additional load.