/Body rewrite

Body rewrite

1
v0.0.1

Traefik Body Rewrite Plugin

Plugin Name: body-rewrite
Compatible with: Traefik v3
Purpose: Rewrites HTTP response bodies dynamically based on request headers using regex(Golang based) patterns. Supports gzip-compressed responses and multiple replacements per response. In fact, this plug-in works like a sub_filter in Nginx.


✨ Features

  • 🔄 Replace one or multiple occurrences in the response body using regex.
  • 📦 Support for gzip-compressed responses.
  • 📝 Use any header value as a dynamic replacement in the body.
  • 🐛 Debug logging for troubleshooting.
  • 💡 Works on JSON, HTML, or plain text bodies.

⚙️ Configuration

http:
middlewares:
rewrite-json:
plugin:
body-rewrite:
headerName: "Origin" # Header to read replacement value from
replacementPattern: "https://origin(/[^\"\\s]*)" # Regex pattern to match in body
replacement: "{header}$1" # Replacement string, {header} is replaced with header value
debug: true # Enable debug logging (optional)
ParameterTypeRequiredDescription
headerNamestringName of the HTTP header whose value will be used in replacements.
replacementPatternstringRegex pattern to search in the body. Supports capture groups.
replacementstringReplacement string. Use {header} to insert the header value dynamically.
debugbooleanEnables debug logging (default: false).

📖 Example

Backend Response:

{
"logo": "https://origin/images/logo.png",
"background": "https://origin/images/bg.png"
}

Request:

curl -H "Origin: https://cdn.example.com" http://localhost/

Rewritten Response:

{
"logo": "https://cdn.example.com/images/logo.png",
"background": "https://cdn.example.com/images/bg.png"
}

📝 Notes

If the specified header is missing, the body is returned unmodified.

Regex should account for line breaks if matching JSON (e.g. https://origin(/[^"\s]*)).

Regex based on Golang Regexp syntax.

Plugin can rewrite multiple occurrences of the pattern in a single response.