Redirect HTTP to HTTPS with Traefik 2 Middleware in K3s
Published Updated 5 years ago
When setting up my new K3s cluster I needed some sort of redirect from HTTP to HTTPS. One option that is often found when searching for this issue is to redirect all traffic with Traefik. This however is not suitable if you just want some services to redirect and not everything in the cluster. Especially if you are using ACME with HTTP challenges – a global redirect would render those challenges useless, as they cannot get responded to (because it redirects away from HTTP to a non-existent HTTPS). A solution to this issue is to redirect only specific services. For this a redirect from HTTP to HTTPS with a Traefik middleware present a viable remedy.
In this example I am using K3s in version v1.21.0+k3s1 which comes with Traefik in version 2.4.8.
The first step is to create a Traefik Middleware resource with a redirectScheme. This scheme will redirect HTTP traffic to HTTPS. The following yaml file can be easily applied to achieve this.
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
name: redirect-https
spec:
redirectScheme:
scheme: https
permanent: true
Now this newly created middleware resource can be used in an Ingress object to tell the ingress to redirect traffic in the aforementioned way. A very important detail which is omitted in the documentation however, is that the name of the resource in the annotation has to have a prefix for the namespace it’s created in. In the example above this is the default namespace. So you need to set this as a prefix and @kubernetescrd always as a suffix to the name of your middleware.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
traefik.ingress.kubernetes.io/router.middlewares: default-redirect-https@kubernetescrd
name: grafana
namespace: grafana
spec:
rules:
- host: grafana.example.com
http:
paths:
- backend:
service:
name: grafana
port:
number: 3000
path: /
pathType: ImplementationSpecific
After editing the annotation in this way, Traefik should now make use of it correctly. You successfully created a redirect from HTTP to HTTPS with a Traefik middleware.
Comments
Comments are hosted on comments.itobey.dev. Loading them sets cookies and shares your IP address with that service.