## Using Traefik 2.2 middlewares with Kubernetes Ingress resources

##### 2020-07-31
traefik middleware Kubernetes ingress redirect auth

Since Traefik 2.0, this feature was possible just with custom IngressRoute resources, but it is now possible with normal Kubernetes Ingress as well.

So, what is the Traefik middleware, anyways? It is a piece of code which is triggered just before the Ingress itself. Here you can find the full list of available directives that you can use to create your middleware. In this article we are going to define two middlewares, one to redirect www.example.io to example.io, so that we make SEO happy and another one for basic authentication. Here is how this would look like using helmfile declaration:

releases:
- name: traefik-resources
chart: incubator/raw
namespace: default
values:
- resources:
- apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
name: basic-auth
spec:
basicAuth:
secret: basic-auth
- apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
name: redirect-no-www
spec:
redirectRegex:
regex: ^https://www\.(.*)
replacement: https://\${1}
permanent: true


As you can see, basic-auth middleware uses basic-auth secret which you can create using the following commands:

htpasswd -c auth your-username
kubectl create secret generic basic-auth --from-file=auth


In order to invoke the basic-auth middleware before your Ingress, you should annotate the desired ingress with the following annotation:

traefik.ingress.kubernetes.io/router.middlewares: default-basic-auth@kubernetescrd


As you can assume, the value of this key is consisted of the namespace where the middleware exists, then dash, then the name of the middleware itself and finally the suffix @kubernetescrd.

The second middleware uses regular expression to find out if your hostname is prefixed with www and in such case it would remove the www prefix and just keep the basic hostname. You may want to do the opposite and in that case you have to modify the regex and the replacement values. At this moment I believe you can guess that we can invoke this middleware using the following annotation at the desired ingress:

traefik.ingress.kubernetes.io/router.middlewares: default-redirect-no-www@kubernetescrd


Traefik was really powerfull ingress option for Kubernetes from the very beginning, but we can say now that it is back to the roots and since the version 2.2 we can use the full set of features together with the traditional Kubernetes resources. I can really recommend you to try Traefik, it is a great product.