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

如何通过Nginx将非标准自定义请求头传递至uWSGI+Flask后端?

解决自定义请求头传递至Flask+uWSGI后端的问题

1. 修正Nginx配置的语法错误

你当前的proxy_set_header行语法完全错误,正确格式是头名称在前,变量在后,头名不需要加$前缀。将错误配置:

proxy_set_header $HTTP_Chart-Type $http_chart_type;

替换为:

proxy_set_header chart_type $http_chart_type;

如果希望后端收到标准化的连字符格式头(如Chart-Type),可改为:

proxy_set_header Chart-Type $http_chart_type;

2. 关闭uWSGI对下划线请求头的过滤

uWSGI默认会丢弃包含下划线的请求头,若要传递chart_type这类带下划线的头,需在uWSGI配置中添加参数:

# uwsgi.ini 配置文件示例
underscores-in-headers = true

或启动uWSGI时直接追加命令行参数:

uwsgi --ini your_config.ini --underscores-in-headers true

3. 在Flask中正确获取请求头

场景1:传递原chart_type头(带下划线)

uWSGI会将这类头转换为大写并添加HTTP_前缀,Flask中获取方式:

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def get_chart_type():
    # 两种获取方式均可
    chart_type = request.headers.get('HTTP_CHART_TYPE')
    # chart_type = request.environ.get('HTTP_CHART_TYPE')
    return f"Chart Type: {chart_type}"

场景2:传递Chart-Type头(带连字符)

Flask会自动将连字符转换为下划线并添加HTTP_前缀,可通过两种方式获取:

chart_type = request.headers.get('HTTP_CHART_TYPE')
# 或更直观的写法
chart_type = request.headers.get('Chart-Type')

4. 验证配置生效

修改配置后重启服务:

# 重启Nginx
sudo systemctl restart nginx

# 重启uWSGI(根据部署方式调整命令)
sudo systemctl restart uwsgi

用curl测试请求头传递:

curl -H "chart_type: line" http://你的域名/

若后端返回Chart Type: line,则配置生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:20:24