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
Official competencies this lesson covers
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.
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:
| Controller | Annotation prefix | Path rewrite is done with |
|---|---|---|
| ingress-nginx (the community NGINX controller) | nginx.ingress.kubernetes.io/ | rewrite-target |
| F5 NGINX Ingress Controller | nginx.org/ | rewrites |
| HAProxy Ingress Controller | haproxy.org/ | path-rewrite |
| Traefik | traefik.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.
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
| Where | Scope | Example |
|---|---|---|
Ingress spec | One Ingress, any controller | host, path, backend, TLS |
| Ingress annotations | One Ingress, one controller | rewrite-target, ssl-redirect |
| Controller ConfigMap | Every Ingress of that controller | default 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:
| Form | Value | Effect |
|---|---|---|
| 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 for | Pod 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
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:
| Piece | Meaning | Captured as |
|---|---|---|
/shop | The literal prefix | not 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 | $2 | Pod receives |
|---|---|---|---|
/shop | (empty) | (empty) | / |
/shop/ | / | (empty) | / |
/shop/cart | / | cart | /cart |
/shop/cart/7?size=m | / | cart/7 | /cart/7?size=m |
/shopping | no match | handled by another rule, or 404 |
Three things have to be true together for this form to work:
- The path is a regular expression with capture groups.
pathTypeisImplementationSpecific.PrefixandExactpaths are validated as plain paths, and controllers reject or misread a pattern there.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
locationblock per path and adds a rewrite directive to it.kubectl -n ingress-nginx exec deploy/ingress-nginx-controller -- cat /etc/nginx/nginx.confshows the result, which is the ground truth when a rewrite does not behave. - The query string survives.
?size=mis 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-regexorrewrite-target, all paths of that host, in every Ingress, are matched as case-insensitive regular expressions, longest pattern first. A plain/apipath 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 applytime 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: /app1 | Redirects 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. UseImplementationSpecific, withuse-regex: "true". /$1where/$2was meant, or a pattern with no groups at all and a target that refers to one.- Unquoted
true,falseor 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 ingressclassand its Pods. - Putting the annotation under
spec, or on the Service. It belongs in the Ingress'smetadata.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.