Search code examples
kubernetesnginx-ingress

Kubernetes NGINX Ingress configmap 301 redirect


Using an NGINX Ingresss in Kubernetes, I can't see a way to forward my traffic from non-www to www, or to another domain etc on a per-host basis

I've tried looking in configmap docs but can't see what I need. Maybe it can go in the ingress itself?

I've also seen an example using annotations but this seems to be ingress-wide, so I couldn't have specific redirects per host


Solution

  • Indeed a redirect is possible with a simple annotation:

    But as you mentioned, it's "Ingress" wide and not configurable per host, per domain or even per path. So you'll have to do it yourself through the ingress.kubernetes.io/configuration-snippet annotation, which gives you a great deal of power thanks to regular expressions:

    kind: Ingress
    apiVersion: extensions/v1beta1
    metadata:
      name: self-made-redirect
      annotations:
        ingress.kubernetes.io/configuration-snippet: |
          if ($host = 'blog.yourdomain.com') {
            return 301 https://yournewblogurl.com;
          }
          if ($host ~ ^(.+)\.yourdomain\.com$) {
            return 301 https://$1.anotherdomain.com$request_uri;
          }
    spec:
      rules:
      - host: ...
    

    If you are not quite used to NGINX, you'll know more about what's possible in the snippet, particularly what is the $host variable right in the NGINX documentation.