|
| 1 | +# Configuring the Caddy Web Server |
| 2 | + |
| 3 | +[The API Platform distribution](index.md) is shipped with [the Caddy web server](https://caddyserver.com). |
| 4 | +The build contains the [Mercure](../core/mercure.md) and the [Vulcain](https://vulcain.rocks) Caddy modules. |
| 5 | + |
| 6 | +Caddy is positioned in front of the web API and of the Progressive Web App. |
| 7 | +It routes requests to either service depending on the value of the `Accept` HTTP header or the extension |
| 8 | +of the requested file. |
| 9 | + |
| 10 | +Using the same domain to serve the API and the PWA [improves performance by preventing unnecessary CORS preflight requests |
| 11 | +and encourages embracing the REST principles](https://dunglas.fr/2022/01/preventing-cors-preflight-requests-using-content-negotiation/). |
| 12 | + |
| 13 | +By default, requests having an `Accept` request header containing the `text/html` media type are routed to the Next.js application, |
| 14 | +except for some paths known to be resources served by the API (e.g. the Swagger UI documentation, static files provided by bundles...). |
| 15 | +Other requests are routed to the API. |
| 16 | + |
| 17 | +Sometimes, you may want to let the PHP application generate HTML responses. |
| 18 | +For instance, when you create your own Symfony controllers serving HTML pages, |
| 19 | +or when using bundles such as EasyAdmin or SonataAdmin. |
| 20 | + |
| 21 | +To do so, you have to tweak the rules used to route the requests. |
| 22 | +Open `api-platform/api/docker/caddy/Caddyfile` and modify the expression. |
| 23 | +You can use [any CEL (Common Expression Language) expression](https://caddyserver.com/docs/caddyfile/matchers#expression) supported by Caddy. |
| 24 | + |
| 25 | +For instance, if you want to route all requests to a path starting with `/admin` to the API, modify the existing expression like this: |
| 26 | + |
| 27 | +```patch |
| 28 | +# Matches requests for HTML documents, for static files and for Next.js files, |
| 29 | +# except for known API paths and paths with extensions handled by API Platform |
| 30 | +@pwa expression `( |
| 31 | + {header.Accept}.matches("\\btext/html\\b") |
| 32 | +- && !{path}.matches("(?i)(?:^/docs|^/graphql|^/bundles/|^/_profiler|^/_wdt|\\.(?:json|html$|csv$|ya?ml$|xml$))") |
| 33 | ++ && !{path}.matches("(?i)(?:^/admin|^/docs|^/graphql|^/bundles/|^/_profiler|^/_wdt|\\.(?:json|html$|csv$|ya?ml$|xml$))") |
| 34 | + ) |
| 35 | +``` |
0 commit comments