Kubernetes nginx ingress configuration for wildcard rule

1/24/2022

I am struggling with the following issues. I have 2 services running. I am using a wildcard for handling subdomains. See the example conf below:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    ingress.kubernetes.io/ssl-redirect: "false"
    kubernetes.io/ingress.class: nginx
    kubernetes.io/ingress.global-static-ip-name: web-static-ip
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/server-alias: www.foo.bar
    nginx.ingress.kubernetes.io/use-regex: "true"
  name: foo-bar-ingress
  namespace: test
spec:
  rules:
  - host: '*.foo.bar'
    http:
      paths:
      - backend:
          serviceName: legacy-service
          servicePort: 80
        path: /(.*)
        pathType: ImplementationSpecific
  - host: foo.bar
    http:
      paths:
      - backend:
          serviceName: new-service
          servicePort: 8080
        path: /(.*)
        pathType: ImplementationSpecific

Using the app in the way that abc.foo.bar -> legacy-service and foo.bar -> new-service work perfectly fine. However, when I access the app with www prefix, it gets under the wildcard subdomain path, meaning www.foo.bar goes into legacy-service, which is what I want to avoid. AFAIU this "www" is caught by this asterisk regexp and goes in the wrong way. I would like it go to new-service.

Is there any way I can achieve this with the nginx ingress configuration?

-- Adam SoliƄski
kubernetes
kubernetes-ingress
nginx
nginx-ingress

1 Answer

1/24/2022

Also redirecting requests from www.foo.bar can be achieved by also specifying the hostname. Please note that the order of the hosts does matter as they are translated into the Envoy filter chain. Therefore, the wildcard host should be the last host.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    ingress.kubernetes.io/ssl-redirect: "false"
    kubernetes.io/ingress.class: nginx
    kubernetes.io/ingress.global-static-ip-name: web-static-ip
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/server-alias: www.foo.bar
    nginx.ingress.kubernetes.io/use-regex: "true"
  name: foo-bar-ingress
  namespace: test
spec:
  rules:
  - host: 'foo.bar'
    http:
      paths:
      - backend:
          serviceName: new-service
          servicePort: 8080
        path: /(.*)
        pathType: ImplementationSpecific
  - host: 'www.foo.bar'
    http:
      paths:
      - backend:
          serviceName: new-service
          servicePort: 8080
        path: /(.*)
        pathType: ImplementationSpecific
  - host: '*.foo.bar'
    http:
      paths:
      - backend:
          serviceName: legacy-service
          servicePort: 80
        path: /(.*)
        pathType: ImplementationSpecific
-- Jonas Breuer
Source: StackOverflow