From 4887b9c716ceb9519b446477fe3cb827a135e058 Mon Sep 17 00:00:00 2001 From: Pamela Fox Date: Fri, 1 Dec 2023 10:01:26 -0800 Subject: [PATCH] Add tips on relative url_for in templates docs --- docs/en/docs/advanced/templates.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 38618aeeb..6ca9fd5a6 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -72,6 +72,17 @@ In this example, it would link to a CSS file at `static/styles.css` with: And because you are using `StaticFiles`, that CSS file would be served automatically by your **FastAPI** application at the URL `/static/styles.css`. +!!! note + The url generated by `url_for` is a full absolute URL, including the protocol. That may not work in a reverse proxy situation, like Traefik or GitHub Codespaces. + If you would instead like it to generate relative URLs, you can override the `url_for` template function in your Python code: + + ```python + templates.env.globals["url_for"] = app.url_path_for + ``` + + Another way to affect the generated URLs is to customize `uvicorn` with arguments like `proxy-headers`, `root-path`, and `forwarded-allow-ips`. + See uvicorn's docs on settings. + ## More details For more details, including how to test templates, check Starlette's docs on templates.