Traefik HTTP redirect to HTTPS

43 Views Asked by At

I've setup a traefik webrouter and redirected TCP80 and TCP443 to it as default. EntryPoints in traefik.toml are web and websecure as you can see here:

[entryPoints]
  [entryPoints.web]
    address = ":80"
  [entryPoints.websecure]
    address = ":443"

[certificatesResolvers.letsencrypt.acme]
  email = "XXXX"
  storage = "/etc/traefik/acme.json"
  [certificatesResolvers.letsencrypt.acme.httpChallenge]
    entryPoint = "web"

[providers.file]
  filename = "/etc/traefik/traefik_dynamic.toml"

Now i tried to implement a rule which listens on HTTP and HTTPS and if clients connect to HTTP it redirects to HTTPS in default. That ist this configuration in traefik_dynamic.toml

[http]
  [http.routers]
    [http.routers.npm]
      entryPoints = ["web"]
      service = "npm"
      rule = "Host(`npm.XXX.de`)"
      middlewares = ["httpsRedirect"]
    [http.routers.npm-secure]
      entryPoints = ["websecure"]
      service = "npm"
      rule = "Host(`npm.XXX.de`)"
      [http.routers.npm.tls]
        certResolver = "letsencrypt"

  [http.services]
    [http.services.npm]
      [http.services.npm.loadBalancer]
        [[http.services.npm.loadBalancer.servers]]
          url = "http://192.168.1.79/"

  [http.middlewares.httpsRedirect.redirectScheme]
    scheme = "https"
    permanent = "true"

But that returns 404 and doesnt work. I already got it working with HTTPS OR HTTP only. But not both (unfortunately i deleted the working HTTPS and HTTP config; stupid me). What would be the correct way to implement a HTTP to HTTPS redirect?

1

There are 1 best solutions below

0
On

Here's two solutions, one that I have on my server and a new one from traefik documentation.

First option

The following should work (modified from yaml syntax so take it with a grain of salt):

    [http.routers.redirecttohttps]:
      [http.routers.redirecttohttps.entryPoints]:
        - web

      [http.routers.redirecttohttps.middlewares]:
        - httpsredirect

      rule: 'HostRegexp(`{host:.+}`)'
      service: noop

It creates a no-operation service for each hostname (modify the regexp if you don't want it for all) and adds the redirect middleware to them.

Second option

Since Traefik documentation these days recommends this, I think this is the better solution:

  [entryPoints.web.http]
    [entryPoints.web.http.redirections]
      [entryPoints.web.http.redirections.entryPoint]
        to = "websecure"
        scheme = "https"

It even seems so straightforward that no explanation is needed.