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"
In my case I needed to have the root domain point to a sub url which is a public folder of my nextcloud instance (without this redirect being shown via the url to the visitor, so this can be a bit of a different use-case than this original gist intents to do). My full docker-compose.yml which is working for this can be found here: https://help.nextcloud.com/t/move-nextcloud-to-sub-url-but-put-a-public-folder-at-root-with-nextcloud-nginx-nginx-docker-gen-all-in-docker/89292/15?u=steffres
The most interesting parts of this compose should be (which of course would still need the context of the rest):
Note that therein, in the first line here a middleware must be defined and named, in my case
custom_repath
which then later is refered to by e.g.traefik.http.middlewares.custom_repath.replacepathregex.regex=...
(I found this a bit tricky that defining your own named thing and referencing this thing is not fully clear from the code if you are referencing a custom defined thing or something pre-defined because it's squeezed into the whole line)And then in the second line, the pattern logic is defined and in the third the replacement. Also note that
$$
is a double escaping$
because it's also a special character in docker-compose.So in my case this logic replaces
cloud.museumsstrasse.at/
withcloud.museumsstrasse.at/intern/s/63KFWGkziffJR8j
(while this not being shown to the visitor, I don't know if that is what you want ... ) but nothing else, e.g.cloud.museumsstrasse.at/intern
is not replaced.If you want to keep the redirected url shown to the visitor, than a slight change must be made, but I don't remember what anymore.