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

在Vercel上为Python Flask应用添加子域名的技术求助

解决Vercel部署Flask多子域名路由问题

一、修改Flask代码

在根路由处理函数中,通过请求的Host头判断当前访问的子域名,返回对应内容:

@app.route(constants.ENDPOINT_ROOT, methods=constants.GET)
def home():
    # 提取不带端口的主机名
    host = request.host.split(':')[0]
    if host == 'link.example.com':
        return jsonify({"message": "link hello"})
    elif host == 'api.example.com':
        return jsonify({"message": "hello"})
    # 其他域名访问时返回原有默认内容
    return jsonify(constants.MESSAGE_ROOT)

二、Vercel配置调整

  1. 添加子域名:
    登录Vercel控制台,进入目标项目,在「Settings」→「Domains」中添加link.example.com,按照提示完成DNS解析(将子域名CNAME指向cname.vercel-dns.com),等待解析生效。

  2. 配置vercel.json保留原始Host头:
    在项目根目录创建或修改vercel.json文件,确保Vercel将原始请求的Host头传递给Flask应用,否则Flask无法正确识别子域名:

{
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/api/index.py",  // 替换为你的Flask入口文件实际路径,比如根目录的app.py就写"/app.py"
      "headers": {
        "Host": "$host"
      }
    }
  ]
}

验证

部署修改后的代码到Vercel,等待部署完成后:

  • 访问api.example.com/会返回{"message": "hello"}
  • 访问link.example.com/会返回{"message": "link hello"}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 02:14:53