How to strip the path prefix in Kubernetes Traefik ingress?

Viewed 1548

I'm using k3s v1.22.7 on Ubuntu 20.04. I want /bar/xyz to be /xyz to the pods. Without the middleware I'm properly routed to the pods, with it I get 404 from Traefik as though the stripping from replacePathRegex/stripPrefix happens before the Ingress path evaluation. Examples online all have it like that though...

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: strip-prefix
spec:
  #replacePathRegex:
  #  regex: ^/(?:[^/]+)/(.*)
  #  replacement: /$1
  stripPrefix:
    prefixes:
      - /bar
      - /baz
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: foo-ingress
  annotations:
    kubernetes.io/ingress.class: traefik
    traefik.ingress.kubernetes.io/router.middlewares: strip-prefix@kubernetescrd
spec:
  rules:
  - host: example.org
    http:
      paths:
      - path: /bar
        pathType: Prefix
        backend:
          service:
            name: foo-service
            port:
              number: 5001
      - path: /baz
        pathType: Prefix
        backend:
          service:
            name: foo-service
            port:
              number: 5002
1 Answers

Looks like the middleware needs the namespace prefixed, so either

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: strip-prefix
  # No namespace defined
spec:
  stripPrefixRegex:
    regex:
    - ^/[^/]+
---
kind: Ingress
metadata:
  annotations:
    traefik.ingress.kubernetes.io/router.middlewares: default-strip-prefix@kubernetescrd

or

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: strip-prefix
  namespace: example # Namespace defined
spec:
  stripPrefixRegex:
    regex:
    - ^/[^/]+
---
kind: Ingress
metadata:
  annotations:
    traefik.ingress.kubernetes.io/router.middlewares: example-strip-prefix@kubernetescrd

should work.

(Source)

Related