Skip to content
LF Cert Trainer

Lesson 119 · Section 9: Networking

Lesson 119: Annotations and rewrite-target: changing the path on its way to the Pod

Why an application behind a path such as /shop answers 404, how annotations switch on one Ingress controller's extra features, how rewrite-target works with and without capture groups, and why none of this is portable between controllers. · 18 min read · 2 min video

1/8Annotations and rewrite-target
0:00 / 2:22

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why it exists

The previous lesson ended with a warning. An Ingress rule for /shop sends matching requests to the shop Service with the path unchanged. The user asked for /shop/cart, so the Pod receives GET /shop/cart.

Most applications are written to live at the root of a site. The shop has pages at /, /cart and /checkout, and knows nothing about a /shop prefix that somebody added in an Ingress. It answers 404 Not Found.

The path arrives unchanged, and the application does not know itas isno such pageClientGET /shop/cartIngress controllerrule: /shopshop Podserves /cart404 Not Foundfrom the application
The path arrives unchanged, and the application does not know it. The Ingress matches /shop/cart and forwards exactly that. The shop application only has a page at /cart, so it answers 404. The Ingress is correct; the path is wrong for the Pod.

Parts:

  • Client (GET /shop/cart)
  • Ingress controller (rule: /shop)
  • shop Pod (serves /cart)
  • 404 Not Found (from the application)

Connections:

  • Client to Ingress controller
  • Ingress controller to shop Pod: as is
  • shop Pod to 404 Not Found: no such page

Everything Kubernetes was asked to do worked: the rule matched, the Service has endpoints, the Pod answered. The 404 comes from the application. The fix is to have the Ingress controller remove the prefix before it forwards the request. That is a rewrite, and with the NGINX-based controllers you ask for it with an annotation.

What it is

Annotations

An annotation is a key and a string value in metadata.annotations. Unlike labels, annotations are not used to select objects. They carry extra information for whoever knows the key. Kubernetes stores them and does not check them.

Ingress controllers use this as their extension mechanism. Each controller documents a list of keys under its own prefix, and reads them from every Ingress it handles:

ControllerAnnotation prefixPath rewrite is done with
ingress-nginx (the community NGINX controller)nginx.ingress.kubernetes.io/rewrite-target
F5 NGINX Ingress Controllernginx.org/rewrites
HAProxy Ingress Controllerhaproxy.org/path-rewrite
Traefiktraefik.ingress.kubernetes.io/A separate Middleware object, named in an annotation

This lesson uses the nginx.ingress.kubernetes.io/ annotations, because they are what the Kubernetes documentation shows and what practice environments use.

Three places where an Ingress controller is configuredportablecontroller specificglobalIngress spechost, path, TLSAnnotationsper IngressConfigMapcontroller defaultsIngress controllermerges all three
Three places where an Ingress controller is configured. The spec is the same for every controller. Annotations change one Ingress and belong to one controller. The controller's ConfigMap changes the defaults for every Ingress it serves.

Parts:

  • Ingress spec (host, path, TLS)
  • Annotations (per Ingress)
  • ConfigMap (controller defaults)
  • Ingress controller (merges all three)

Connections:

  • Ingress spec to Ingress controller: portable
  • Annotations to Ingress controller: controller specific
  • ConfigMap to Ingress controller: global
WhereScopeExample
Ingress specOne Ingress, any controllerhost, path, backend, TLS
Ingress annotationsOne Ingress, one controllerrewrite-target, ssl-redirect
Controller ConfigMapEvery Ingress of that controllerdefault timeouts, log format

rewrite-target

nginx.ingress.kubernetes.io/rewrite-target holds the path that the controller sends to the Pod instead of the original one. It has two forms:

FormValueEffect
Fixed/ (or any fixed path)Every matching request is forwarded with exactly this path
With capture groups/$2, /app/$1 ...The new path is built from parts of the original path

How it works

The fixed form

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: shop
  namespace: web
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  rules:
    - http:
        paths:
          - path: /shop
            pathType: Prefix
            backend:
              service:
                name: shop
                port:
                  number: 80
Client asks forPod receives
/shop/
/shop//
/shop/cart/
/shop/css/site.css/

Everything collapses to /. For an application with one page this is all you need, and it is the form most practice tasks use. For a real site it breaks: the style sheet and the cart page both return the home page.

The form with capture groups

To keep the rest of the path, describe the path as a regular expression, put brackets around the part you want to keep, and refer to it in the annotation.

metadata:
  name: shop
  namespace: web
  annotations:
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  ingressClassName: nginx
  rules:
    - http:
        paths:
          - path: /shop(/|$)(.*)
            pathType: ImplementationSpecific
            backend:
              service:
                name: shop
                port:
                  number: 80
rewrite-target with a capture groupmatchesfillsnew pathRequest path/shop/cart/7Path pattern/shop(/|$)(.*)Group $1/Group $2cart/7rewrite-target/$2shop Pod receives/cart/7
rewrite-target with a capture group. The path pattern captures what follows /shop into the second group. The annotation builds the new path from that group, so the Pod receives the path it expects.

Parts:

  • Request path (/shop/cart/7)
  • Path pattern (/shop(/|$)(.*))
  • Group $1 (/)
  • Group $2 (cart/7)
  • rewrite-target (/$2)
  • shop Pod receives (/cart/7)

Connections:

  • Request path to Path pattern: matches
  • Path pattern to Group $1
  • Path pattern to Group $2
  • Group $2 to rewrite-target: fills
  • rewrite-target to shop Pod receives: new path

Read the pattern /shop(/|$)(.*) piece by piece:

PieceMeaningCaptured as
/shopThe literal prefixnot captured
(/|$)Either a slash or the end of the path. This stops /shopping from matching$1
(.*)Everything that follows$2

Groups are numbered from left to right in the order their opening brackets appear. The annotation /$2 means "a slash, then whatever the second group caught":

Client asks for$1$2Pod receives
/shop(empty)(empty)/
/shop//(empty)/
/shop/cart/cart/cart
/shop/cart/7?size=m/cart/7/cart/7?size=m
/shoppingno matchhandled by another rule, or 404

Three things have to be true together for this form to work:

  1. The path is a regular expression with capture groups.
  2. pathType is ImplementationSpecific. Prefix and Exact paths are validated as plain paths, and controllers reject or misread a pattern there.
  3. use-regex: "true" is set, so the controller treats the path as a pattern.

Annotations apply to the whole Ingress

An annotation sits in metadata, so it applies to every path of that Ingress. If /shop needs a rewrite and /api must keep its path, they cannot share an Ingress. Create two Ingress objects with the same host; the controller merges them into one virtual host.

Ingress shop   annotations: rewrite-target    path /shop(/|$)(.*)  -> Service shop
Ingress api    no annotations                 path /api            -> Service api

This is the standard answer to "the rewrite broke my other paths".

Under the hood · What the controller does with the annotation, and its side effects
  • It becomes proxy configuration. The controller generates one location block per path and adds a rewrite directive to it. kubectl -n ingress-nginx exec deploy/ingress-nginx-controller -- cat /etc/nginx/nginx.conf shows the result, which is the ground truth when a rewrite does not behave.
  • The query string survives. ?size=m is not part of the path that is matched or rewritten; it is passed on.
  • Regular expressions spread across the host. With this controller, as soon as one Ingress for a host uses use-regex or rewrite-target, all paths of that host, in every Ingress, are matched as case-insensitive regular expressions, longest pattern first. A plain /api path on the same host then behaves like a pattern that matches anything starting with /api, including /apiold.
  • Redirects from the application. If the shop answers with a redirect to /login, the browser goes to /login, not /shop/login. A rewrite fixes requests, not the links and redirects the application produces. An application that must live under a prefix is better configured with that prefix itself.
  • Admission check. The controller usually installs a validating webhook. A broken pattern or a forbidden annotation is rejected at kubectl apply time with a message from that webhook, not silently ignored.
  • Snippet annotations. Annotations that inject raw proxy configuration are disabled by default in current releases, because anyone who may create an Ingress could use them to read the controller's secrets.

Other annotations worth recognising

You do not need to memorise these. Recognise what they are for, and know that the list lives in the controller's documentation, not in the Kubernetes API reference.

Annotation (prefix nginx.ingress.kubernetes.io/)What it does
ssl-redirect: "false"Stops the automatic redirect from HTTP to HTTPS. The redirect is on by default once the Ingress has a tls section
force-ssl-redirect: "true"Redirects to HTTPS even when the Ingress has no tls section
app-root: /app1Redirects requests for / to this path
backend-protocol: "HTTPS"Talks HTTPS (or GRPC) to the Pods instead of plain HTTP
proxy-body-size: "8m"Largest request body accepted, for uploads
proxy-read-timeout: "120"Seconds to wait for the Pod's answer
whitelist-source-range: "10.0.0.0/8"Only these client addresses may connect
canary: "true" with canary-weight: "10"Sends a share of the traffic to a second Ingress's backend

Using it

Example · A single-page application under a prefix

Task: requests for /wear must reach Service wear-service on port 8080, and requests for /watch must reach video-service on port 8080, in namespace app-space. Both applications serve their page at /.

kubectl -n app-space create ingress apps --class=nginx \
  --rule="/wear*=wear-service:8080" \
  --rule="/watch*=video-service:8080" \
  --annotation nginx.ingress.kubernetes.io/rewrite-target=/

kubectl create ingress accepts --annotation key=value, so the whole task is one command. Test both paths:

curl -s -o /dev/null -w '%{http_code}\n' http://203.0.113.10/wear      # 200
curl -s -o /dev/null -w '%{http_code}\n' http://203.0.113.10/watch     # 200

Example · Add or change an annotation on an existing Ingress

An Ingress shop exists and the application returns 404 for /shop. Add the rewrite without editing YAML:

kubectl -n web annotate ingress shop nginx.ingress.kubernetes.io/rewrite-target=/
kubectl -n web annotate ingress shop nginx.ingress.kubernetes.io/ssl-redirect=false --overwrite
kubectl -n web describe ingress shop | grep -A3 Annotations
Annotations:  nginx.ingress.kubernetes.io/rewrite-target: /
              nginx.ingress.kubernetes.io/ssl-redirect: false

--overwrite is needed when the key already exists. A key followed by a minus sign removes it: kubectl annotate ingress shop nginx.ingress.kubernetes.io/ssl-redirect-. On the command line kubectl annotate stores the value as a string for you, so =false needs no quotes here.

Example · Strip the prefix but keep the rest of the path

The shop has many pages, so the fixed form is not enough.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: shop
  namespace: web
  annotations:
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  ingressClassName: nginx
  rules:
    - host: example.com
      http:
        paths:
          - path: /shop(/|$)(.*)
            pathType: ImplementationSpecific
            backend:
              service:
                name: shop
                port:
                  number: 80

Prove it by looking at what the application received:

curl -s -H "Host: example.com" http://203.0.113.10/shop/cart/7 > /dev/null
kubectl -n web logs deploy/shop --tail=1
10.244.0.12 - - "GET /cart/7 HTTP/1.1" 200 612

The access log of the Pod shows /cart/7. The prefix is gone and the rest of the path is intact.

Example · Decide whether you need a rewrite at all

Before adding an annotation, find out who returns the 404:

kubectl -n web port-forward svc/shop 8080:80 &
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/shop/cart   # 404: the app has no such path
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/cart        # 200: the app serves it at the root

If the application answers on /cart but not on /shop/cart, you need a rewrite. If it answers on /shop/cart directly, it already knows its prefix and a rewrite would break it.

Tricks

Common mistakes

  • Expecting the Ingress to strip the prefix by itself. It never does. Without a rewrite the Pod gets the full original path.
  • Using the fixed form for a multi-page application. rewrite-target: / sends every sub-path to the home page.
  • A capture-group pattern with pathType: Prefix. Use ImplementationSpecific, with use-regex: "true".
  • /$1 where /$2 was meant, or a pattern with no groups at all and a target that refers to one.
  • Unquoted true, false or numbers in YAML. Annotation values must be strings.
  • A typo in the annotation key, or the wrong prefix for the installed controller. No error, no effect. Check which controller runs with kubectl get ingressclass and its Pods.
  • Putting the annotation under spec, or on the Service. It belongs in the Ingress's metadata.annotations.
  • One Ingress for paths that need different treatment. Annotations cover every path of the object.
  • Blaming the Ingress for a 404 that comes from the application. Check the Pod's log first.

Recap

  • An Ingress forwards the request path unchanged. An application that lives at / needs the prefix removed.
  • Annotations are how one specific controller is told to do more than the Ingress spec can express.
  • nginx.ingress.kubernetes.io/rewrite-target: / forwards every matching request as /.
  • To keep the rest: path /shop(/|$)(.*), pathType: ImplementationSpecific, use-regex: "true", target /$2.
  • Annotations apply to the whole Ingress and to one controller only. Quote the values, copy the keys, and read the Pod's log to see the path that arrived.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Publish an application under a path prefix it does not know about, so that the prefix is removed before the request reaches the pod.

    Build · Level 2 · standard · target 15 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.