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

Flask反向代理未完整转发请求导致静态资源404错误如何解决

问题原因
  • 路由匹配范围过窄:当前仅给根路径/绑定了代理处理逻辑,/test、/css/style.css等其余路径没有对应处理函数,Flask直接返回404状态码。
  • 代理请求路径写死:就算匹配到了对应路径,现有代码的请求目标永远是目标站点的根路径,不会把用户请求的子路径同步到目标站点,无法拿到对应子路径的静态资源。
  • 页面资源引用逻辑:你请求/test返回的页面中,静态资源都是根路径相对地址,浏览器会直接向本地代理服务发起对应路径的请求,没有代理逻辑自然加载失败。
修复方案

1. 调整路由匹配规则

新增通配符路由,捕获所有路径的请求,统一交给代理函数处理:

# 匹配根路径
@app.route('/', methods=['GET'])
# 匹配任意长度的子路径
@app.route('/<path:path>', methods=['GET'])

2. 动态拼接目标请求地址

将用户请求的路径、查询参数都拼接到目标站点地址上,保证能请求到对应资源:

# path默认值为空适配根路径请求
def proxy(path=''):
    headers = {"User-Agent": str(request.user_agent)}
    # 拼接完整目标地址,自动处理路径拼接的斜杠问题
    from urllib.parse import urljoin
    target_url = urljoin(SITE_NAME, path)
    # 透传原请求的查询参数
    resp = requests.get(target_url, headers=headers, params=request.args)

完整可运行修复代码

from flask import Flask, request, Response
import requests
from urllib.parse import urljoin

app = Flask(__name__)
SITE_NAME = 'https://www.whatsmyua.info'

@app.route('/', methods=['GET'])
@app.route('/<path:path>', methods=['GET'])
def proxy(path=''):
    headers = {"User-Agent": str(request.user_agent)}
    target_url = urljoin(SITE_NAME, path)
    resp = requests.get(target_url, headers=headers, params=request.args)
    excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
    headers = [(name, value) for name, value in resp.raw.headers.items() if name.lower() not in excluded_headers]
    response = Response(resp.content, resp.status_code, headers)
    print(request.user_agent)
    print(request.path)
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:39:04