You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js挂载FastAPI后经反向代理跳转至HTTP问题求助

解决Vue.js挂载FastAPI后反向代理重定向问题

原因分析与修复方案

1. 修正FastAPI StaticFiles的重定向逻辑

当StaticFiles开启html=True时,访问/dist会自动重定向到/dist/,但FastAPI默认会用服务器原始IP和端口生成重定向URL,而非反向代理的域名。

修改挂载代码,添加root_path参数(若域名直接指向FastAPI服务,root_path设为空字符串;若为子路径代理,设为对应子路径):

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount(
    "/dist",
    StaticFiles(directory="../../frontend/src/dist", html=True, root_path=""),
    name="static"
)

2. 同步Vue的路径配置

若Vue使用history路由模式,需确保路由base与FastAPI挂载路径完全匹配:

  • 修改vue.config.js:
module.exports = {
  publicPath: '/dist/', // 与FastAPI挂载路径一致
  devServer: {
    historyApiFallback: true // 开发环境支持history模式 fallback
  }
}
  • 修改Vue路由配置:
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory('/dist/'), // 与publicPath保持一致
  routes: [/* 你的路由列表 */]
})

3. 补充Nginx Proxy Manager反向代理配置

在反向代理的自定义配置中添加以下规则,确保重定向时保留域名:

# 替换重定向URL中的IP端口为域名
proxy_redirect http://$host:$server_port/ https://your-domain.com/;
# 传递正确的请求头给FastAPI
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

内容的提问来源于stack exchange,提问作者crazywolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 22:28:16