Skip to content

Instantly share code, notes, and snippets.

@kekru
Last active November 22, 2024 05:09
Show Gist options
  • Save kekru/d088be6a3fa844089ae62d80c077bb38 to your computer and use it in GitHub Desktop.
Save kekru/d088be6a3fa844089ae62d80c077bb38 to your computer and use it in GitHub Desktop.
Traefik redirect / (root) to sub path with Docker labels

Traefik: redirect base or root path to a subpath

This is tested with Traefik 1.7

This is how to redirect the root or base path to a sub path in Traefik using Docker labels:
Goals

  • https://example.com -> https://example.com/abc/xyz/
  • https://example.com/ -> https://example.com/abc/xyz/
  • https://example.com/something -> no redirect

We will match <begin of line>https://<any chars but not slash AS group1><slash or nothing><end of line>
and replace it with https://<group1>/abc/xyz/.
In regex we have to escape a / character by \/. In docker-compose labels we need to escape again, so that it becomes \\\\/.
We also need to escape $ to $$ because of docker-compose.

labels:
  - "traefik.frontend.rule=Host:example.com"
  - "traefik.frontend.redirect.regex=^https:\\\\/\\\\/([^\\\\/]+)\\\\/?$$"
  - "traefik.frontend.redirect.replacement=https://$$1/abc/xyz/"
  - "traefik.port=80"
  - "traefik.enable=true"
@gogromat
Copy link

Thank you, I solved a root redirect for mailpit

http:
  middlewares:
    mailpit-mail-prefix:
      redirectRegex:
        regex: "^https://([^/]+)/?$"
        replacement: "https://${1}/mail/"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment