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.
http:middlewares:rewrite-json:plugin:body-rewrite:headerName: "Origin" # Header to read replacement value fromreplacementPattern: "https://origin(/[^\"\\s]*)" # Regex pattern to match in bodyreplacement: "{header}$1" # Replacement string, {header} is replaced with header valuedebug: true # Enable debug logging (optional)
| Parameter | Type | Required | Description |
|---|---|---|---|
headerName | string | ✅ | Name of the HTTP header whose value will be used in replacements. |
replacementPattern | string | ✅ | Regex pattern to search in the body. Supports capture groups. |
replacement | string | ✅ | Replacement string. Use {header} to insert the header value dynamically. |
debug | boolean | ❌ | Enables debug logging (default: false). |
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"}
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.