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

部署在Render.com后Flask子域名路由无法正常工作

解决Flask子域名路由不生效的问题

可能的原因及修复步骤

1. 确认Render项目已绑定子域名

Render需要在项目的「Domains」设置中添加子域名 toothpaste.buytogo.space,而非仅添加DNS记录:

  • 进入你的Render项目后台,找到「Domains」选项卡
  • 点击「Add Domain」,输入 toothpaste.buytogo.space
  • 等待Render验证DNS记录完成(通常需要几分钟到几小时)

2. 配置Flask识别反向代理的真实主机头

Render作为反向代理,会将原始请求的主机名放在 X-Forwarded-Host 头中,Flask默认不会读取该头,导致无法正确识别子域名。需添加中间件并调整配置:

修改你的Flask代码:

from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix

app = Flask(__name__)
# 配置信任代理,让Flask读取X-Forwarded-*系列头
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
app.config['SERVER_NAME'] = 'buytogo.space'
app.config['PREFERRED_URL_SCHEME'] = 'https'  # 强制使用HTTPS协议

@app.route('/')
def main_index():
    return "You are visiting the main domain"

@app.route('/', subdomain='toothpaste')
def product_landing_1():
    return "Welcome to the TOOTHPASTE subdomain"

@app.route('/', subdomain='cooler')
def product_landing_2():
    return "Welcome to the COOLER subdomain"

@app.route('/', subdomain='<subdomain>')
def wildcard_subdomain(subdomain):
    return f"You are visiting the subdomain: {subdomain}"

if __name__ == '__main__':
    app.run()

3. 验证DNS记录是否生效

用命令行工具检查子域名解析状态:

nslookup toothpaste.buytogo.space
# 或
dig toothpaste.buytogo.space

确保返回的IP地址与 domain-testing-server-for-landing.onrender.com 的IP一致,若不一致,等待DNS缓存刷新(最长可能24小时)。

4. 确认路由匹配顺序

你的代码中具体子域名路由(toothpaste、cooler)在通配路由之前定义,这个顺序是正确的——Flask会优先匹配具体路由,无需调整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:29:56