Kubernetes nginx ingress: How to redirect foo.example.org to example.org?

My ingress currently looks like this:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  tls:
    - hosts:
        - example.org
        - app.example.org
      secretName: prod-tls
  rules:
    - host: example.org
      http:
        paths:
          - path: /
            backend:
              serviceName: app-service
              servicePort: 80
    - host: app.example.org
        http:
          paths:
              - path: /
                backend:
                  serviceName: app-service
                  servicePort: 80

But now I want to redirect app.example.org to example.org instead. How can I do this?

I found this example using ingress.kubernetes.io/configuration-snippet but I don't know what domains that will apply to?

I'm using Helm nginx-ingress-1.37.0; app ver 0.32.0.


Solution 1:

I found this example using ingress.kubernetes.io/configuration-snippet: but I don't know what domains that will apply to?

It's easier to reason about that configuration when you have two Ingresses, one just for "hosting" the configuration-snippet: and the other for doing the real work:

---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  tls:
    - hosts:
        - example.org
      secretName: prod-tls
  rules:
    - host: example.org
      http:
        paths:
          - path: /
            backend:
              serviceName: app-service
              servicePort: 80
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-redirect
  annotations:
    kubernetes.io/ingress.class: nginx
    # this should be covered by the annotation on the other ingress
    # since it will renew the same certificate
    # cert-manager.io/cluster-issuer: letsencrypt-prod
    ingress.kubernetes.io/configuration-snippet: |
        rewrite ^/(.*)$ https://example.org/$1 permanent;
spec:
  tls:
    - hosts:
        - app.example.org
      secretName: prod-tls
  rules:
    - host: app.example.org
      http:
          paths:
              - path: /
                backend:
                  serviceName: app-service
                  servicePort: 80