Skip to content

PRIHLOP/traefik-body-rewrite

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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)
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).

📖 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.

About

Web page body rewrite middleware for Traefik

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors