如何为DigitalOcean Droplet上的Django API服务器配置HTTPS加密?
由于Let's Encrypt不支持直接为IP地址颁发可信证书,自签名证书是快速实现IP+HTTPS的方案,但移动端需要手动信任该证书才能正常连接。
步骤1:生成自签名SSL证书
在docker-ubuntu-droplet上执行以下命令:
# 生成有效期365天的私钥和证书 openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /opt/api_ssl/private.key -out /opt/api_ssl/certificate.crt
执行时按提示填写信息,其中Common Name必须填写你的Droplet公网IP地址。
步骤2:配置HTTPS访问Django API
推荐用Nginx反向代理的方式(比直接让Django加载证书更稳定):
- 安装Nginx:
apt update && apt install nginx -y
- 创建Nginx配置文件
/etc/nginx/sites-available/api-ssl:
server { listen 443 ssl; server_name YOUR_DROPLET_IP; # 替换为你的Droplet公网IP ssl_certificate /opt/api_ssl/certificate.crt; ssl_certificate_key /opt/api_ssl/private.key; location / { proxy_pass http://localhost:8000; # 假设Django服务运行在8000端口 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
- 启用配置并重启Nginx:
ln -s /etc/nginx/sites-available/api-ssl /etc/nginx/sites-enabled/ nginx -t && systemctl restart nginx
步骤3:移动端信任自签名证书
将生成的certificate.crt文件发送到移动端,在系统设置中安装并信任该证书,否则移动端会拒绝连接该API。
如果需要生产环境的可信证书,建议给Droplet IP绑定一个子域名(比如api.domain_name.it),再用Let's Encrypt免费证书实现HTTPS。
步骤1:配置DNS解析
在你的域名服务商后台添加一条A记录,将子域名(如api.domain_name.it)指向docker-ubuntu-droplet的公网IP,等待DNS生效。
步骤2:获取Let's Encrypt证书
在Droplet上安装Certbot及Nginx插件:
apt update && apt install certbot python3-certbot-nginx -y
运行Certbot自动获取证书并配置Nginx:
certbot --nginx -d api.domain_name.it
按提示完成操作即可,Certbot会自动生成证书并配置HTTPS规则。
步骤3:配置反向代理到Django
如果Certbot未自动添加反向代理规则,手动修改Nginx配置文件(通常在/etc/nginx/sites-available/api.domain_name.it.conf),添加以下内容:
location / { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }
重启Nginx:
systemctl restart nginx
步骤4:移动端调用API
此时移动端可通过https://api.domain_name.it/api/get-customers/安全访问API,无需手动信任证书。
内容的提问来源于stack exchange,提问作者Matteo Citterio

