How to Write Redirects in Kubernetes’ Nginx Ingress

Are you using kubernetes and want to redirect a www website to its non-www counterpart, or vice versa? Hey, me too! 😃

I recently re-launched the website for dictate.life and in the midst of planning the deployment I realized that there were a couple of simple requirements that I hadn’t been fully aware of at first:

I’m familiar with performing this sort of task using a 301 redirect in a traditional Apache or Nginx environment, but I was unfamiliar with how to do this in a Kubernetes environment. Here’s how I ended up accomplishing it:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  namespace: default
  name: my-nginx-ingress
  annotations:
    ...other annotations...
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($host = 'myhost.com') {
        return 301 https://www.myhost.com$request_uri;
      }

The neat thing about this redirect is that it not only redirects requests to the root path, /, but also to any other path. So if someone visits http://dictate.life/about, they’ll be taken to the correct HTTPS-enabled, www-toting version of the url 🎉

This isn’t the only way to use the configuration-snippet option of Kubernetes’ nginx ingress. I’ve found that the above snippet best suits my needs, but let’s say that regardless of the URL input by the user, you always wanted to redirect them to the root. This would be a useful situation if you were moving to a new website where the URLs didn’t match. In that case, you’d simply leave off the $request_uri portion, e.g.

nginx.ingress.kubernetes.io/configuration-snippet: |
  if ($host = 'myhost.com') {
    return 301 https://www.myhost.com;
  }

This is the best way I’ve found to apply configuration changes to one ingress, assuming that you have only one. Nginx ingress also supports altering the default configuration of multiple ingresses at once, using ConfigMaps. More info on that can be found here: https://kubernetes.github.io/ingress-nginx/examples/customization/custom-headers/

Want to learn more? Come watch me code or ask me a question on my Twitch stream! https://www.twitch.tv/malgasm/

updated 5.13.2022

Infrastructure / Architecture, Software Engineering