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

Flask 2.2.5反向代理下重定向URL slug重复问题求助

Flask 2.2.5 Slug重定向错误问题解析

问题场景

在Flask 2.2.5版本搭配反向代理(ReverseProxy)部署时,出现slug重定向异常,页面无法正常显示。

应用代码

@mainapp.route('/<slug>/', methods=['GET','POST'])
def introduction(slug):
    Title = "Hello World"
    Start = "Welcome, press start to begin."
    Start_Button = "Start"
    if request.method == 'POST':
         return redirect(slug + "/nextpage")

错误现象

点击提交按钮后,服务器日志显示请求URL为:

[09/Jul/2023 01:18:08] "GET /folder/slug_name/slug_name/nextpage

参考配置

mainapp.config["APPLICATION_ROOT"] = "/folder" #主目录或子文件夹路径。
mainapp.wsgi_app = ReverseProxied(mainapp.wsgi_app,script_name=mainapp.config["APPLICATION_ROOT"])

错误原因

  • 相对路径拼接导致重复:代码中直接用slug + "/nextpage"生成的是相对路径,Flask会基于当前请求的URL路径(/folder/slug_name/)拼接该相对路径,最终形成/folder/slug_name/slug_name/nextpage,出现slug重复的错误。
  • 未适配反向代理配置:未使用Flask内置的URL生成机制,忽略了APPLICATION_ROOT的配置,导致反向代理的子目录路径未被正确纳入重定向逻辑。

解决办法

推荐方案:使用url_for生成正确URL

利用Flask的url_for函数自动适配APPLICATION_ROOT配置,生成绝对路径:

from flask import url_for

# 先定义子页面路由
@mainapp.route('/<slug>/nextpage/', methods=['GET'])
def next_page(slug):
    # 子页面逻辑
    pass

# 修改原视图的重定向逻辑
@mainapp.route('/<slug>/', methods=['GET','POST'])
def introduction(slug):
    Title = "Hello World"
    Start = "Welcome, press start to begin."
    Start_Button = "Start"
    if request.method == 'POST':
         return redirect(url_for('next_page', slug=slug))

备选方案:手动生成绝对路径

若不想使用url_for,可直接拼接根路径开头的绝对路径:

if request.method == 'POST':
     return redirect(f"/{slug}/nextpage")

注:此方式硬编码路径,灵活性较差,不推荐在多环境部署场景使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 05:22:59