一、为什么需要NginxNode.js应用直接运行在3000端口上直接用IP加端口访问http://你的IP:3000/api/xxx这种方式有几个问题不安全没有HTTPS加密数据明文传输不专业用户看到的是IP和端口而不是域名不方便微信小程序要求API必须使用HTTPSNginx作为反向代理可以解决所有这些问题。二、Nginx安装与基本配置sudoaptupdatesudoaptinstallnginxsudosystemctl start nginxsudosystemctlenablenginx反向代理配置# /etc/nginx/sites-available/jianji server { listen 80; server_name api.jianji.com; location / { proxy_pass http://localhost:3000; 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; } }启用配置sudoln-s/etc/nginx/sites-available/jianji /etc/nginx/sites-enabled/sudonginx-t# 测试配置是否正确sudosystemctl reload nginx三、HTTPS证书配置微信小程序要求API必须使用HTTPS。简记往来使用Let’s Encrypt免费证书。安装Certbotsudoaptinstallcertbot python3-certbot-nginx获取证书sudocertbot--nginx-dapi.jianji.comCertbot会自动修改Nginx配置添加HTTPS支持并设置自动续期。配置HTTPS后的Nginxserver { listen 443 ssl; server_name api.jianji.com; ssl_certificate /etc/letsencrypt/live/api.jianji.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/api.jianji.com/privkey.pem; location / { proxy_pass http://localhost:3000; 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; } } # HTTP自动跳转HTTPS server { listen 80; server_name api.jianji.com; return 301 https://$server_name$request_uri; }四、微信小程序合法域名配置HTTPS配置完成后需要在微信小程序后台配置合法域名路径小程序后台 → 开发 → 开发管理 → 开发设置 → 服务器域名将https://api.jianji.com添加到request合法域名中。五、常见问题和排查问题1证书不被信任确认使用的是Let’s Encrypt或其他受信任CA签发的证书不要使用自签名证书问题2443端口不通检查云服务器安全组是否开放443端口检查防火墙sudo ufw allow 443/tcp问题3证书续期失败确保80端口可访问Certbot验证需要手动续期sudo certbot renew --dry-run六、总结Nginx HTTPS 的配置流程安装Nginx→ 配置反向代理获取SSL证书→ 使用Let’s Encrypt免费证书配置HTTPS→ 修改Nginx配置配置微信合法域名→ 在小程序后台添加HTTPS是微信小程序的基本要求也是用户信任的基础。下一篇我们来聊聊日志系统设计——没有日志出了问题只能靠猜。评论区聊聊你的HTTPS配置遇到过什么坑