rewrites: async () => [
{
source: "/api/:slug*",
destination: "http://backend:8000/:slug*"
}
]
整个批次都在码头堆栈中运行(这是主机名来的地方),我最终得到了这样的标题:
backend
然后,我通过电子邮件发送了FastAPI应用程序的链接。 我这样构建了这样的URL:
host: backend:8000
x-forwarded-host: localhost:3000
我已经用
@app.get("/verify")
async def verify(token: str):
...
@app.post("/signup")
async def signup(body: SignupRequest, request: Request) -> str:
user = add_user(body.username, body.email)
token = user.get_signup_token()
url = request.url_for("verify").include_query_params(token=token)
email_verification(body.email, url)
return ""
设置了FastApi,以便正确重写路径。
产生的URL为
root_path="/api"
。 我希望它是
http://backend:8000/api/verify
(即具有实际的托管URL,而不是docker堆栈URL)。 我尝试添加这样的中间件:
http://localhost:3000/api/verify
@app.middleware("http")
async def rewrite_host_header(request: Request, call_next):
if "x-forwarded-host" in request.headers:
request.headers["host"] = request.headers["x-forwarded-host"]
return await call_next(request)
,但这也不会改变
request.url = request.url.replace(host=request.headers["x-forwarded-for"])
的输出。
我的意思是如何配置它,以便URL发出正确的方案,主机名和端口?Edit要添加:我还尝试过设置
request.url_for(...)
X-Forwarded-Proto
,X-Forwarded-Port
和
X-Forwarded-Prefix
,使用
X-Forwarded-For
直接向FastApi提出请求,然后删除NextJS步骤。 这对curl
我认为问题是uvicorn(如果您使用的话)默认情况下不信任代理标题,除非指定。
根据fastapi文档
关于在代理后面的docker上部署fastapi的文档,您需要启用代理标题。 a gitchitionally tharlette提供了有关乌维科恩中间件的信息,用于处理代理标头。uvicorngithub代码还提供了有关如何处理代理标题的洞察力。