NGINX Ingress Routing based on Header

10/29/2021

I have an nginx-ingress calling a custom auth-service before sending requests to the backend service, using this simple ConfigMap and Ingress:

apiVersion: v1
kind: ConfigMap
metadata:
  ...
data:
  global-auth-url: auth-service-url:8080/authenticate
  global-auth-method: GET
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: "nginx"
  ...
spec:
  rules:
  - host: host1
    http:
      paths:
      - backend:
          serviceName: backend-service
          servicePort: 8080 

Now I need something different.

How can I send requests, all with the same "Host" header, through different flows, one with auth-service and connected to backend-service1 and the other without any authentication and connecting to backend-service2?

To be clear, and using the custom header "Example-header: test"

  1. If "Example-header" is "test", authenticate via my auth-service before sending to backend-service, as it's done now.
  2. If "Example-header" is not defined, I want to send requests to a different backend service and do not use auth-service in the process.

I tried a couple of things, namely having 2 Ingresses, one with global-auth-url and the other with nginx.ingress.kubernetes.io/enable-global-auth: "false" but the auth-service is always called.

Can I do this with NGINX, or do I have to use Istio or Ambassador?

-- João Pereira
kubernetes
nginx
nginx-ingress

1 Answer

11/23/2021

One way you can achieve this behavior is by abusing the canary feature.

For your backend-service, create a normal Ingress, e. g.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-backend
spec:
  ingressClassName: nginx
  rules:
  - host: localhost
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: backend-service
            port:
              number: 80

Create a second Ingress for you auth-service with enabled canary and set the header name and value, e. g.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-auth
  annotations:
    nginx.ingress.kubernetes.io/canary: "true"
    nginx.ingress.kubernetes.io/canary-by-header: Example-header
    nginx.ingress.kubernetes.io/canary-by-header-value: test
spec:
  ingressClassName: nginx
  rules:
  - host: localhost
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: auth-service
            port:
              number: 80

Now, every request with Example-header: test routes to auth-service. Any other value, e. g. Example-header: some-value, will not route to auth-service but rather go to your backend-service.

-- malte.h
Source: StackOverflow