ReplacePathRegex

Updating the Path Before Forwarding the Request (Using a Regex)

The ReplaceRegex replaces the path of a URL using regex matching and replacement.

Configuration Examples

Docker

  1. # Replace path with regex
  2. labels:
  3. - "traefik.http.middlewares.test-replacepathregex.replacepathregex.regex=^/foo/(.*)"
  4. - "traefik.http.middlewares.test-replacepathregex.replacepathregex.replacement=/bar/$$1"

Kubernetes

  1. # Replace path with regex
  2. apiVersion: traefik.containo.us/v1alpha1
  3. kind: Middleware
  4. metadata:
  5. name: test-replacepathregex
  6. spec:
  7. replacePathRegex:
  8. regex: ^/foo/(.*)
  9. replacement: /bar/$1

Consul Catalog

  1. # Replace path with regex
  2. - "traefik.http.middlewares.test-replacepathregex.replacepathregex.regex=^/foo/(.*)"
  3. - "traefik.http.middlewares.test-replacepathregex.replacepathregex.replacement=/bar/$1"

Marathon

  1. "labels": {
  2. "traefik.http.middlewares.test-replacepathregex.replacepathregex.regex": "^/foo/(.*)",
  3. "traefik.http.middlewares.test-replacepathregex.replacepathregex.replacement": "/bar/$1"
  4. }

Rancher

  1. # Replace path with regex
  2. labels:
  3. - "traefik.http.middlewares.test-replacepathregex.replacepathregex.regex=^/foo/(.*)"
  4. - "traefik.http.middlewares.test-replacepathregex.replacepathregex.replacement=/bar/$1"

File (YAML)

  1. # Replace path with regex
  2. http:
  3. middlewares:
  4. test-replacepathregex:
  5. replacePathRegex:
  6. regex: "^/foo/(.*)"
  7. replacement: "/bar/$1"

File (TOML)

  1. # Replace path with regex
  2. [http.middlewares]
  3. [http.middlewares.test-replacepathregex.replacePathRegex]
  4. regex = "^/foo/(.*)"
  5. replacement = "/bar/$1"

Configuration Options

General

The ReplacePathRegex middleware will:

  • replace the matching path with the specified one.
  • store the original path in a X-Replaced-Path header.

Tip

Regular expressions and replacements can be tested using online tools such as Go Playground or Regex101.

regex

The regex option is the regular expression to match and capture the path from the request URL.

replacement

The replacement option defines the replacement path format, which can include captured variables.

Warning

Care should be taken when defining replacement expand variables: $1x is equivalent to ${1x}, not ${1}x (see Regexp.Expand), so use ${1} syntax.