Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 336
Ben Gannaway Avatar asked Nov 28 '18 11:11

Ben Gannaway


2 Answers

Indeed a redirect is possible with a simple annotation:

  • nginx.ingress.kubernetes.io/permanent-redirect: https://www.gothereinstead.com
  • nginx.ingress.kubernetes.io/from-to-www-redirect: "true"

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.

like image 54
Clorichel Avatar answered Sep 19 '22 13:09

Clorichel


To redirect all traffic regardless of using HTTP or HTTPS from example.com and www.example.com to newdomain.example.com I ended up with the following solution.

In this example I'm also using cert-manager.io to request the certs for www.example.com and example.com.

The redirect is done using the annotation nginx.ingress.kubernetes.io/permanent-redirect

kind: Ingress
apiVersion: extensions/v1beta1
metadata:
  name: redirect-example-to-newdomain
  annotations:
    kubernetes.io/ingress.class: "nginx"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
    nginx.ingress.kubernetes.io/permanent-redirect: https://newdomain.example.com
spec:
  tls:
    - hosts:
      - example.com
      - www.example.com
      secretName: example.com-tls
  rules:
    - host: example.com
    - host: www.example.com
like image 35
0xC0DEBA5E Avatar answered Sep 22 '22 13:09

0xC0DEBA5E