How to Redirect Www to Non Www Traffic in Traefik Kubernetes Ingress

When using Traefik as your Kubernetes ingress controller you might want to redirect any requests to your top-level www domain (for instance www.citizix.com) to its non-www variant (citizix.com). You can use this snippet to create a Traefik IngressRoute and Traefik Middleware that will do just that.

If you want to redirect one or multiple websites individually from non-www to www in Traefik (or vice versa), you just need to define one (or two) middleware in the dynamic configuration file!

Prerequisites

  • A running instance of Traefik v2 in a Kubernetes cluster
  • kubectl access to the Kubernetes cluster
  • External IP address of the server/VM for testing

Snippet

Create the Middleware

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: redirect-www
  namespace: citizix
spec:
  redirectRegex:
    regex: "^https?://www.citizix.com(.*)"
    replacement: "https://citizix.com$1"
    permanent: true

Then add an IngressRoute:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: ingressroute
  namespace: citizix
spec:
  entryPoints:
    - web
    - websecure
  routes:
    - match: Host(`www.citizix.com`)
      kind: Rule
      services:
        - name: citizix-app
          port: 80
      middlewares:
        - name: redirect-www

This is how the Ingress for the site looks like

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod-issuer
  labels:
    app.kubernetes.io/instance: citizix
    app.kubernetes.io/name: citizix-app
    argocd.argoproj.io/instance: citizix
  name: citizix-app
  namespace: citizix
spec:
  ingressClassName: traefik
  rules:
    - host: citizix.com
      http:
        paths:
          - backend:
              service:
                name: citizix-app
                port:
                  number: 80
            path: /
            pathType: ImplementationSpecific
  tls:
    - hosts:
        - citizix.com
        - www.citizix.com
      secretName: citizix-tls

Try it out

Try it out with

1
2
3
4
$ curl -v https://citizix.com/ --resolve citizix.com:443:{your server IP}

301 Moved Permanently
Location: https://citizix.com/

Checkout these as well

comments powered by Disqus
Citizix Ltd
Built with Hugo
Theme Stack designed by Jimmy