Home > OS >  Traefik - Middleware redirectRegex doesn't work
Traefik - Middleware redirectRegex doesn't work

Time:01-21

I have a simple website running in my Kubernetes cluster and exposed to the Internet using Traefik. My Ingress object looks like this (the only things I've changed here are the name and domain names):

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-staging
    kubernetes.io/ingress.class: traefik
  name: my-cool-website
  namespace: default
spec:
  rules:
  - host: my-cool-website.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-cool-website
            port:
              number: 80
  - host: www.my-cool-website.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-cool-website
            port:
              number: 80
  tls:
  - hosts:
    - my-cool-website.com
    - www.my-cool-website.com
    secretName: my-cool-website-tls

This works. It allows me to access the site either from my-cool-website.com or from www.my-cool-website.com. But what I'd like to have happen is that if someone visits the former, that Traefik automatically redirects them to the latter. I found a couple of guides online that recommended creating a Traefik middleware, so I did just that, but unfortunately it doesn't work as intended. Here is my middleware definition:

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: my-cool-website-force-www
spec:
  redirectRegex:
    regex: ^https?://my-cool-website.com/(.*)
    replacement: https://www.my-cool-website.com/${1}

And then I add the following annotation back to the ingress object:

traefik.ingress.kubernetes.io/router.middlewares: my-cool-website-force-www

But as soon as I do that, it breaks my web app. By that I mean, when that annotation is applied, instead of serving my website, I start seeing a generic nginx page that looks like this when I try to access the domain (and also it does not do the redirect):

Hello World generic Traefik response

I have to assume this Hello World page is being served by Traefik as some sort of generic default page, as it definitely does not originate from my pod. So that tells me something about this middleware (or perhaps how I'm calling it with the annotation) isn't working. What am I missing?

CodePudding user response:

I figured it out, by port-forwarding to the Traefik Dashboard and looking at the service there. It was showing an error for the middleware not found. I then clicked over to the middlewares and realized that they end up with a longer canonical name. So in my annotation I had to change the reference from my-cool-website-force-www to default-my-cool-website-force-www@kubernetescrd and then everything worked.

  • Related