How to add slash at the end of path automatically based on Traefik?

This article was last updated on: February 7, 2024 pm

preface

Traefik is a modern HTTP reverse proxy and load balancer that makes it easy to deploy microservices.

Traefik works with multiple existing infrastructure components (Docker, Swarm patterns, Kubernetes, Marathon, Consul, Etcd, Rancher, Amazon ECS…). Integrate and configure yourself automatically and dynamically.

Series:

In practice, a very common need, the URL entered by the user is e-whisper.com/alert-manager, if nothing is done will return 404, need to automatically add slashes into e-whisper.com/alert-manager/, how to implement based on Traefik on K8S?

The answer is: redirectRegex MiddleWare + regularity.

Actual combat

Create MiddleWare directly as follows:

1
2
3
4
5
6
7
8
9
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
name: auto-add-slash
spec:
redirectRegex:
permanent: true
regex: ^(https?://[^/]+/[-a-z0-9_]+)$
replacement: ${1}/

📝 The instructions are as follows:

The regular match is:

  • ^(https?: Content that begins with https or http;? Indicates that the previous character is matched 0 or 1 times
  • [^/]+/: matches the URL first / Previous content
  • [-a-z0-9_]+: Matches the first one / The content that follows is often alphanumeric and hyphenated and underlined

ultimately^(https?://[^/]+/[-a-z0-9_]+)$ Examples of what the group matches are:https://e-whisper.com/monitor-alertmanager, and replace it with:${1}/, i.e. the matching group is followed by it /, examples such as:https://e-whisper.com/monitor-alertmanager

🐾 note:

The above MiddleWare may not be able to adapt to all situations, readers can grasp its main points and make appropriate adjustments according to their needs.

IngressRoute uses

Use it directly like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: alertmanager
spec:
routes:
- kind: Rule
match: Host(`e-whisper.com`) && PathPrefix(`/alertmanager`)
middlewares:
- name: auto-add-slash
services:
- name: alertmanager
port: 9093

🎉🎉🎉 Finish!

EOF