nginx-ingress add custom header for a specific path

Viewed 4197

I have the following nginx-ingress in a kubernetes environment

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "cache-control: no-store";
      more_set_headers "MyCustomHeader: Value";
spec:
  rules:
  - http:
      paths:
      - backend:
          serviceName: svc1
          servicePort: 80
          # Want to add the custom headers in this path only
        path: /
      - backend:
          serviceName: svc2
          servicePort: 80
        path: /cacheable-path

I have a couple of headers that I want to set Cache-Control and MyCustomHeader. But I want these headers to be set only for the root path / and not for other routes (like /cacheable-path).

How to achieve this ? Adding the annotation causes the header to be appended to all the responses. I want the headers to be added to a specific path only.

1 Answers

It is not possible to add headers for a specific path in a single Ingress resource. You will have to create two Ingress resources.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "cache-control: no-store";
      more_set_headers "MyCustomHeader: Value";
spec:
  rules:
  - http:
      paths:
      - backend:
          serviceName: svc1
          servicePort: 80
        path: /

Without header

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - http:
      paths:
      - backend:
          serviceName: svc2
          servicePort: 80
        path: /cacheable-path
Related