Skip to main content

Modify the Requests and the Responses

Traefik Hub API Gateway allows you to modify the requests and the responses according to your needs. It is possible to rewrite the path (adding or stripping the prefix or replacing the values), to compress the response, or to manipulate the headers.


Add Prefix

Adds the prefix /foo to every request:

apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: add-foo
namesapce: apps
spec:
addPrefix:
prefix: /foo

Compress

Compress the response according to the Accept-Encoding header value:

apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: compress
namesapce: apps
spec:
compress: {}

Manipulate Headers

Adding Headers to the Request and the Response

The following example adds the X-Script-Name header to the proxied request to the upstream and the X-Custom-Response-Header header to the response from the upstream.

---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: middleware-header
namespace: apps
spec:
headers:
customRequestHeaders:
X-Script-Name: "test"
customResponseHeaders:
X-Custom-Response-Header: "value"

Adding and Removing Headers

In the following example, requests are proxied to the upstream with an extra X-Script-Name header while their X-Custom-Request-Header header gets stripped, and upstream responses are stripped of their X-Custom-Response-Header header.

---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: middleware-header
spec:
headers:
customRequestHeaders:
X-Script-Name: "test" # Adds
X-Custom-Request-Header: "" # Empty value removes the header
customResponseHeaders:
X-Custom-Response-Header: "" # Empty value removes the header

Replace Path

Replace the request path with /foo:

---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: middleware-replacepath
spec:
replacePath:
path: /foo

Strip Prefix

It exists two middlewares to strip the prefix:

  • StripPrefix: Strip prefixes that are equals to the value given in parameter.
  • StripPrefixRegex: Strip prefixes that match the regular expression given in parameter.

In the example below, the middleware strips the prefix /foo/$value with $value being any alphabetic value:

apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: middleware-stripprefixregex
spec:
stripPrefixRegex:
regex:
- "/foo/[a-z]+"