kubernetes kubernetes/extras kubernetes/networking
Core Idea
Ingress paths often do not match backend paths, so NGINX’s
rewrite-targetannotation strips the public prefix before forwarding; without it the backend receives/watchit never knew about and returns 404.
- The lab shape:
http://:/watchandhttp://:/wearare routed internally to each app’s own URL, which has no/watchor/wearin it.- The annotation works like search and replace on the matched path:
replace(path, rewrite-target).- Regex form shown in the note:
path: /something(/|$)(.*)withrewrite-target: /$2to keep capture groups.
Different ingress controllers have different options that can be used to customise the way it works. NGINX Ingress controller has many options that can be seen here. I would like to explain one such option that we will use in our labs. The Rewrite target option.
Our watch app displays the video streaming webpage at
http://:/
Our wear app displays the apparel webpage at
http://:/
We must configure Ingress to achieve the below. When user visits the URL on the left, his/her request should be forwarded internally to the URL on the right. Note that the /watch and /wear URL path are what we configure on the ingress controller so we can forward users to the appropriate application in the backend. The applications don’t have this URL/Path configured on them:
http://:/watch –> http://:/
http://:/wear –> http://:/
Without the rewrite-target option, this is what would happen:
http://:/watch –> http://:/watch
http://:/wear –> http://:/wear
Notice watch and wear at the end of the target URLs. The target applications are not configured with /watch or /wear paths. They are different applications built specifically for their purpose, so they don’t expect /watch or /wear in the URLs. And as such the requests would fail and throw a 404 not found error.
To fix that we want to “ReWrite” the URL when the request is passed on to the watch or wear applications. We don’t want to pass in the same path that user typed in. So we specify the rewrite-target option. This rewrites the URL by replacing whatever is under rules->http->paths->path which happens to be /pay in this case with the value in rewrite-target. This works just like a search and replace function.
For example: replace(path, rewrite-target)
In our case: replace(“/path”,”/”)
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: test-ingress
namespace: critical-space
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- http:
paths:
- path: /pay
backend:
serviceName: pay-service
servicePort: 8282
In another example given here, this could also be:
replace(“/something(/|2”)
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$2
name: rewrite
namespace: default
spec:
rules:
- host: rewrite.bar.com
http:
paths:
- backend:
serviceName: http-svc
servicePort: 80
path: /something(/|$)(.*)