Flask路由HTTP正常HTTPS异常:EC2部署故障求助
问题:Flask应用部署EC2 Ubuntu后HTTPS下仅根路由可用,其他路由返回404
现象
本地运行Flask应用时所有路由正常,但部署到EC2 Ubuntu服务器并通过Gunicorn启动后,仅根路由/在HTTPS下可访问,其他路由(如/someForm、/submit)均返回404错误。HTTP协议下所有路由可正常响应。
app.py核心代码
@app.route('/') def index(): return render_template("someForm.html") @app.route('/someForm', methods=['GET', 'POST']) def interestForm(): args = request.args args = args.to_dict() emailID = args.get('email') # 自定义Python逻辑 return render_template("someForm.html", somevariable=Value1, somevariable=value2) @app.route('/submit', methods=['GET']) def submit(): args = request.args args = args.to_dict() email = args.get('email') # 更新数据库对应邮箱表单值的后端逻辑 if updateTable(email, updateDic)==1: return redirect("someURL") else: return render_template("someForm.html", error_message = "Issue with updating") if __name__ == '__main__': app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True app.run(debug=True, host='0.0.0.0', port=8000, threaded=True)
部署配置
- Gunicorn启动命令:
nohup gunicorn -b 0.0.0.0:8000 app:app &
- Nginx配置(
/etc/nginx/sites-available/default):
upstream flaskhelloworld { server 127.0.0.1:8000; } # 上方省略其他配置 location / { try_files $uri $uri/ =404; include proxy_params; proxy_set_header Host $host; proxy_pass http://flaskhelloworld; } # 下方省略其他配置
- 额外配置:通过Cloudflare管理DNS,Certbot签发SSL证书。
测试结果
curl https://www.domain_name.com返回正常HTML内容curl https://www.domain_name.com/someForm返回404页面:
<!doctype html> <html lang=en> <title>404 Not Found</title> <h1>Not Found</h1> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
特殊情况
HTTP协议下所有路由可正常响应,例如curl http://domain_name.com/someForm?email=kaushal@gmail.com返回200状态码及正确内容。
解决方案
问题出在Nginx的try_files指令上:try_files $uri $uri/ =404;会优先尝试匹配服务器本地的静态文件或目录,当找不到对应资源时直接返回404,不会将请求转发给Flask应用。
方案1:移除try_files指令(适合无独立静态资源需求的场景)
修改Nginx的location /配置为:
location / { include proxy_params; proxy_set_header Host $host; proxy_pass http://flaskhelloworld; }
方案2:保留静态文件支持(适配Flask static目录)
如果应用有静态资源需要直接由Nginx处理,可单独添加静态文件的location块:
location /static { alias /path/to/your/flask/app/static; } location / { include proxy_params; proxy_set_header Host $host; proxy_pass http://flaskhelloworld; }
修改完成后重启Nginx:
sudo systemctl restart nginx
调整后所有HTTPS请求会正确转发到Flask应用,路由即可正常工作。
内容的提问来源于stack exchange,提问作者Kaushal Bhavsar
相关产品推荐
相关产品推荐

