public

Traefik middleware application like a boss

Redirecting requests to HTTPS from HTTP is a relatively straight forward process: create the middleware and then apply the middleware.

Latest Post Speed kills software engineering. by Matthew Davis public

Redirecting requests to HTTPS from HTTP is a relatively straight forward process: create the middleware and then apply the middleware.

Where most get confused and begin going down the preverbal rabbit hole is when trying to combine both the http and https entryPoints into the same IngressRoute.

To handle this redirect scenario you need to create two separate IngressRoute objects for http and https respectively.

Create the Middleware

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: http-to-https
  namespace: traefik
spec:
  redirectScheme:
    scheme: https
    permanent: true

Create the HTTP IngressRoute

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: http
  namespace: test
spec:
  entryPoints:
    - http
  routes:
    - match: Host(`api.matthewdavis.io`) && PathPrefix(`/`)
      kind: Rule
      middlewares:
        - name: default-http-to-https@kubernetescrd
      services:
        - name: whoami
          port: 80

Create the HTTPS IngressRoute

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: https
  namespace: test
spec:
  entryPoints:
    - https
  routes:
    - kind: Rule
      match: Host(`api.matthewdavis.io`)
      services:
        - name: whoami
          port: 80
  tls:
    secretName: tls-traefik
    options:
      name: traefik-tls-options
      namespace: default

To recap, the following MUST be true:

  1. When referencing the middleware name it must start with the namespace and end with @kubernetesccrd (i.e.: default-http-to-https@kubernetescrd).
  2. You must NOT have a tls declaration in your http IngressRoute objects.

Additional

In case you need another middleware that you can test with and customize things a bit more:

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: headering
spec:
  headers:
    customRequestHeaders:
      X-Script-Name: "itainteasy"
    customResponseHeaders:
      X-Custom-Response-Header: "tryharder"

See also

Matthew Davis

Published a year ago