用于尾部斜杠的FastAPI重定向返回非SSL链接

问题描述:

当我们调用端点并由于缺少尾部斜杠而发生重定向时,遇到了一个问题.如下图所示,当向 https ://.../notifications发送请求时,FastAPI服务器以重定向到 http 的响应://...通知/

Running into an issue when we call an endpoint and a redirect occurs due to a missing trailing slash. As you can see in the image below, when a request is made to https://.../notifications, the FastAPI server responds with a redirect to http://...notifications/

我怀疑这是应用程序配置问题,而不是服务器配置问题.有谁知道如何解决此问题?

I suspect that it's an app configuration issue rather than a server configuration issue. Does anyone have an idea of how to resolve this issue?

这是因为您的应用程序不信任覆盖该方案的反向代理的标头(已通过的 X-Forwarded-Proto 标头当它处理TLS请求时).

This is because your application isn't trusting the reverse proxy's headers overriding the scheme (the X-Forwarded-Proto header that's passed when it handles a TLS request).

有几种方法可以解决此问题:

There's a few ways we can fix that:

  • 如果直接从 uvicorn 服务器运行应用程序,请尝试使用标志-forwarded-allow-ips'*'.

  • If you're running the application straight from uvicorn server, try using the flag --forwarded-allow-ips '*'.

如果您正在运行 gunicorn ,则还可以设置标志-forwarded-allow-ips =" *" .

If you're running gunicorn you can set as well the flag --forwarded-allow-ips="*".

重要提示: * 仅应用作测试,因为它会使您的应用程序信任 X-Forwarded-* 来自任何来源的标题.建议您阅读 uvicorn的文档

Important: the * should be used only as a test, as it'll lead your application to trust the X-Forwarded-* headers from any source. I suggest you read uvicorn's docs and gunicorn's docs for a deeper knowledge of what to set in this flag and why.