Nginx annotation for sub-path redirection in a single K8S ingress Object

Vineet Kumar
1 min readJan 16, 2024

--

Redirect HTTP traffic or rewrite URLs using Kubernetes ingress annotations and Nginx ingress controller. This article explains annotations usage and their effect on the resulting nginx.conf configuration file.

Example1 :-
For example in an ingress, only “/help” redirects to a service and its sub-paths (/help directory should not be required inside the image), and “/” will redirect to a different service name and its subpaths so the ingress code will be

apiVersion: networking.k8s.io/v1beta1 
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/rewrite-target: /
name: destination-home
namespace: myNamespace
spec:
rules:
- host: nginx.doamin.name
http:
paths:
- backend:
serviceName: http-svc-name
servicePort: 80
path: /help(/|$)(.*)

Example2:-

ingress controller and ingress resource running with all /DevOps mapped to DevOps service in the backend. When I try to hit “http://hostname/devops" things work and I get a page (although without CSS and styles) with a set of hyperlinks for example one of them is “logs”.

When I click on the “logs” hyperlink, it redirects me to http://hostname/logs whereas I need it to be http://hostname/devops/logs.

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$2
name: rewrite
namespace: default
spec:
rules:
- host: master1.dev.local
http:
paths:
- backend:
serviceName: http-service-name
servicePort: 80
path: /devops(/|$)(.*)

More use cases will be added in the future.

Enjoy!!!

--

--