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

添加SSL证书后Flask应用出现404错误求助

问题描述

在AWS Lightsail上部署的Flask应用,添加SSL证书前Webhook及各类请求均正常工作,添加证书后所有路由都返回404错误。

请求代码

url = "http://api-dev.xyz.io:8000/webhook"
data = {'foo' : 'bar'}
headers = {'content-type' : 'application/json'}
r = requests.post(url, json=data, headers=headers)

错误日志

"[33mPOST /webhook HTTP/1.1[0m" 404 -

应用代码

import toml
import datetime

Config = toml.load("config.toml")

app = Flask(__name__)

if __name__ == "__main__":
    context = (Config["SSLInfo"]["ssl_cert"], Config["SSLInfo"]["ssl_key"])
    app.run(debug=True, ssl_context=context, host="0.0.0.0", port=8000)



@app.route("/webhook", methods=["POST"])
def webhook():
    if request.method == "POST":
        print("Data received from Webhook is: ", request.json)
        return "Webhook received!"
解决方案

1. 修复路由注册顺序

你的Flask代码里,路由/webhook定义在app.run()之后。当脚本作为主程序运行时,app.run()会启动服务器并阻塞后续代码执行,导致路由根本没被注册到应用中。

调整代码顺序,把路由定义移到app.run()之前,同时补上缺失的request导入:

import toml
import datetime
from flask import Flask, request  # 补充request导入

Config = toml.load("config.toml")

app = Flask(__name__)

@app.route("/webhook", methods=["POST"])
def webhook():
    if request.method == "POST":
        print("Data received from Webhook is: ", request.json)
        return "Webhook received!"

if __name__ == "__main__":
    context = (Config["SSLInfo"]["ssl_cert"], Config["SSLInfo"]["ssl_key"])
    app.run(debug=True, ssl_context=context, host="0.0.0.0", port=8000)

2. 修正请求协议

启用SSL后应用使用HTTPS服务,但你的请求代码仍用http协议,会导致请求无法正确到达服务(除非配置了HTTP转HTTPS)。把请求URL改成HTTPS:

url = "https://api-dev.xyz.io:8000/webhook"

3. 检查Lightsail防火墙配置

确保AWS Lightsail实例的防火墙开放了8000端口(你的应用端口),允许HTTPS流量通过;如果后续改用默认443端口,也要同步开放该端口。

4. 验证SSL证书配置

确认config.toml中填写的SSL证书和密钥路径正确,文件存在且权限允许应用读取,避免因证书加载失败导致服务异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:55:02