如何访问 NGINX 代理背后的 FastAPI SwaggerUI 文档? [英] How to Access FastAPI SwaggerUI Docs Behind an NGINX proxy?
问题描述
希望你能帮助我,这是我遇到的问题:
我的前端和后端服务器都运行在同一个 AWS EC2 实例上.因此,我创建了这样的 NGINX 配置:
Both of my frontend and backend servers runs on the same AWS EC2 instance. Because of this I have created a NGINX config like this:
server {
server_name NAME;
listen 80 default_server;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_http_version 1.1;
}
location /api/ {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_http_version 1.1;
}
}
因此,对 http://public_ip/api/" 的任何请求都会路由到 FastAPI 后端服务器,而对另一个端点的所有其他请求都会路由到前端 SPA.
So any request to the "http://public_ip/api/" routed to the FastAPI backend server while every other request to another endpoint routed to the frontend SPA.
这在大多数情况下效果很好.但是,如果我尝试访问 FastAPI /api/docs" 或 /api/redoc" 路由,则会出现问题.例如,当我调用 /api/docs" 端点时,有一个对 http://public_ip/openapi.json" 地址的请求.这显然不是以 "/api" 开头的端点.所以 NGINX 阻止它并提出一个错误的请求.
This works quite good mostly. However there is an issue if I try to access FastAPI "/api/docs" or "/api/redoc" routes. When I call the "/api/docs" endpoint for instance, there is a request to the "http://public_ip/openapi.json" address. And this isn't an endpoint starting with "/api" obviously. So NGINX blocks it and raises a bad request.
https://fastapi.tiangolo.com/advanced/behind-a-proxy/#about-proxies-with-a-stripped-path-prefix
我找到了本指南,但似乎这与我的问题完全无关.至少我是这么理解的.
I found this guide but it seems like this isn't related to my problem at all. At least I understand it that way.
感谢任何帮助.提前致谢.
推荐答案
将 'openapi_url' 参数传递给 FastAPI() 似乎是一个不错的解决方案.已通过 openapi_url='/api/openapi.json' 并且已针对 docs 和 redoc 进行了修复.感谢任何其他/更好的解决方案来处理可能发生的所有重定向.
Passing 'openapi_url' argument to the FastAPI() seems like good solution. Passed openapi_url= '/api/openapi.json' and it's fixed for both docs and redoc. Any other/better solution to handle all redirects that may occur is appreciated.
api = FastAPI(title="API_NAME",
description="API_DESC",
version="0.2.0",
docs_url='/api/docs',
redoc_url='/api/redoc',
openapi_url='/api/openapi.json')
这篇关于如何访问 NGINX 代理背后的 FastAPI SwaggerUI 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!