Erguotou
Erguotou

Reputation: 215

How to add url prefix for server api with traefik?

I'm using traefik v2 as gateway. I have a frontend container running with host https://some.site.com which powered by traefik.

Now I have a micro-service server with multi services and all of them are listening on 80 port. I want to serve the backend server on path https://some.site.com/api/service1, https://some.site.com/api/service2 ...

I have tried traefik.http.routers.service1.rule=(Host(some.site.com) && PathPrefix(/api/service1)) but not worked and traefik.http.middlewares.add-api.addprefix.prefix=/api/service1 not worked too;

How can I implement this?

Upvotes: 3

Views: 5653

Answers (2)

Sen Alexandru
Sen Alexandru

Reputation: 2283

Assuming you want to call <url>/api/my-service/products, there are two approaches:

  1. Having a route like api/my-service/products defined, PathPrefix(`/api/my-service`) will suffice.
  2. If your route is defined only as /products, then you need to strip the prefix as in the snippet below:
labels:
  - "traefik.http.routers.<service-name>.rule=PathPrefix(`/your-prefix`)"
  - "traefik.http.middlewares.<middleware-name>.stripprefix.prefixes=/your-prefix"
  - "traefik.http.routers.<service-name>.middlewares=<middleware-name>@docker"

Strip prefix is required as it removes prefixes from the path before forwarding the request.

Upvotes: 1

呆胶布
呆胶布

Reputation: 21

Can you post your services' docker-compose configuration? If you use middlewares, you may need to specify the service. Like

traefik.http.routers.service1.middlewares=add-api
traefik.http.middlewares.add-api.addprefix.prefix=/api/service1

Upvotes: 2

Related Questions