Ingress Annotations and Rewrite Target
Luke Hebert
- 2 minutes read - 406 wordsThe rewrite-target annotation in the NGINX Ingress controller maps user-facing URL paths (such as /watch and /wear) to backend services that do not expect those paths, preventing 404 errors. Two examples demonstrate both a simple rewrite and a regex-based rewrite.
Additional Note
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://watch-service:port/.
Our wear app displays the apparel webpage at http://wear-service:port/.
We must configure Ingress to achieve the following. When a user visits the URL on the left, the request should be forwarded internally to the URL on the right. Note that the /watch and /wear URL paths are what we configure on the ingress controller so we can forward users to the appropriate application in the backend. The applications do not have this URL/path configured on them:
http://ingress-service:ingress-port/watch --> http://watch-service:port/
http://ingress-service:ingress-port/wear --> http://wear-service:port/Without the rewrite-target option, this is what would happen:
http://ingress-service:ingress-port/watch --> http://watch-service:port/watch
http://ingress-service:ingress-port/wear --> http://wear-service:port/wearNotice 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 do not expect /watch or /wear in the URLs. 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 do not want to pass in the same path that the 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("/pay", "/")
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: 8282In 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(/|$)(.*)