A Traefik middleware plugin that automatically adds the X-Forwarded-For header to HTTP requests using the client's remote IP address.
This plugin extracts the client's IP address from the request's RemoteAddr field and sets it as the X-Forwarded-For header if one doesn't already exist. This is useful for:
The plugin safely handles malformed remote addresses by failing gracefully and passing the request through unchanged.
A common problem occurs when you have both direct requests to Traefik and requests coming through a Layer 7 load balancer. In this scenario:
X-Forwarded-For headers, so IP allowlists work with the actual client IPX-Forwarded-For headers, but IP allowlists see the load balancer's IP instead of the client IPThis creates an inconsistent situation where you can't reliably use Traefik's IP allowlist middleware with ipStrategy settings.
This plugin solves the problem by ensuring all requests have consistent X-Forwarded-For headers:
X-Forwarded-For → Plugin does nothingX-Forwarded-For → Plugin adds it using the client IPNow you can reliably use Traefik's IP allowlist with ipStrategy:
middlewares:forward-headers:plugin:forward-middleware:enabled: trueip-allowlist:ipAllowList:sourceRange:- "192.168.1.0/24"- "10.0.0.0/8"ipStrategy:depth: 1 # Use the rightmost IP in X-Forwarded-For# ORexcludedIPs: # Exclude known load balancer IPs, you can also use CIDR ranges- "192.168.100.1"- "192.168.100.2"- "192.168.100.0/16"http:routers:my-router:middlewares:- forward-headers # Apply FIRST- ip-allowlist # Apply SECOND
Important: The forward middleware must be applied before the IP allowlist middleware in the chain.
# Static configurationexperimental:plugins:forward-middleware:moduleName: github.com/hiasr/forwardmiddlewareversion: v0.1.0
Here is an example of a file provider dynamic configuration (given here in YAML), where the interesting part is the http.middlewares section:
# Dynamic configurationhttp:routers:my-router:rule: host(`demo.localhost`)service: service-fooentryPoints:- webmiddlewares:- forward-headersservices:service-foo:loadBalancer:servers:- url: http://127.0.0.1:5000middlewares:forward-headers:plugin:forward-middleware:enabled: true