k8s / lightweight redirect

k8s / lightweight redirect

  • Written by
    Walter Doekes
  • Published on

Spinning up pods just to for parked/redirect sites? I think not.

Recently, I had to HTTP(S)-redirect a handful of hostnames to elsewhere. Pointing them into our well maintained K8S cluster was the easy thing to do. It would manage LetsEncrypt certificates automatically using cert-manager.io.

From the cluster, I could spin up a service and an nginx deployment with a bunch of redirect/302 rules.

However, spinning up one or more nginx instances just to have it do simple redirects sounds like overkill. After all, the ingress controller already runs nginx. Why not have it do the 302s?

apiVersion: extensions/v1beta1
kind: Ingress
    cert-manager.io/cluster-issuer: http01-issuer
    nginx.ingress.kubernetes.io/server-snippet: |
      # Do not match .well-known, or we get no certs.
      location ~ ^/($|[^.]) {
        return 302 https://target-url.example.com;
        #return 302 https://target-url.example.com/$1;
        #add_header Content-Type text/plain;
        #return 200 'This domain is parked';
  name: my-redirects
  - host: this-domain-redirects.example.com
      - backend:
          serviceName: dummy
          servicePort: 65535
        path: /
        pathType: ImplementationSpecific
  - hosts:
    - this-domain-redirects.example.com
    secretName: this-domain-redirects.example.com--tls

Using the nginx.ingress.kubernetes.io/server-snippet we can hook in a custom nginx snippet that does the redirecting for us.

Adding the http with backend config in the rules is mandatory. But you can point it do a non-existent dummy service, as seen above.

And if you want parked domains instead of redirected domains, simply replace return 302 https://target-url.example.com; with return 200 'This domain is parked';.

Back to overview Newer post: apt / downgrading back to current release Older post: traverse path permissions / namei