在云服务器上部署微信小程序(通常指后端服务+静态资源),Nginx 和 Node.js 的配合是经典且高效的技术选型。Nginx 负责反向X_X、负载均衡、静态文件服务和 SSL 终止,Node.js 负责业务逻辑处理。
以下是基于国内主流云厂商(如阿里云、腾讯云)最佳实践的配置指南,分为 架构设计、Node.js 配置、Nginx 配置 和 关键注意事项 四个部分。
一、 核心架构思路
小程序后端通常包含两类请求:
- API 接口请求:动态数据交互,由 Node.js 处理。
- 静态资源请求:图片、JS、CSS 等,由 Nginx 直接返回,减轻 Node.js 压力。
流量走向:
客户端 -> HTTPS (Nginx) -> HTTP (Nginx) -> Node.js API
注意:Nginx 与 Node.js 之间使用内网 IP 或
localhost通信,无需 HTTPS,提升性能。
二、 Node.js 服务配置
Node.js 应用应绑定到本地回环地址,避免直接暴露端口给公网,增强安全性。
1. 基础 Express/Koa 示例代码
// app.js
const express = require('express');
const app = express();
// 解析 JSON 请求体
app.use(express.json());
// 健康检查接口
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// 示例 API
app.post('/api/login', (req, res) => {
// 模拟登录逻辑
const { code } = req.body;
if (!code) {
return res.status(400).json({ error: 'Missing code' });
}
// 此处可调用微信服务器换取 openid
res.json({ openid: 'mock_openid_123' });
});
// 启动服务,仅监听 localhost
const PORT = 3000;
app.listen(PORT, '127.0.0.1', () => {
console.log(`Server running on http://127.0.0.1:${PORT}`);
});
2. 生产环境进程管理
不要直接用 node app.js 启动,建议使用 PM2 进行进程守护、日志管理和自动重启。
# 安装 PM2
npm install -g pm2
# 启动应用
pm2 start app.js --name "wx-backend"
# 设置开机自启
pm2 startup
pm2 save
三、 Nginx 配置详解
Nginx 配置文件通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/conf.d/default.conf。
1. 完整 Nginx 配置示例
# /etc/nginx/conf.d/wx-app.conf
server {
# 监听 443 端口(HTTPS)
listen 443 ssl;
server_name your-domain.com; # 替换为你的域名
# --- SSL 证书配置 ---
# 阿里云/腾讯云通常提供一键下载证书,路径如下
ssl_certificate /etc/nginx/ssl/your-domain.pem;
ssl_certificate_key /etc/nginx/ssl/your-domain.key;
# SSL 优化参数
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# --- 静态资源处理 ---
# 如果小程序前端有打包好的 HTML/JS/CSS,放在 /usr/share/nginx/html/dist
location / {
root /usr/share/nginx/html/dist;
index index.html;
try_files $uri $uri/ /index.html; # SPA 路由支持
}
# --- 图片/文件缓存 ---
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
root /usr/share/nginx/html/dist;
expires 30d; # 缓存 30 天
add_header Cache-Control "public, immutable";
}
# --- API 反向X_X ---
location /api/ {
# 移除 /api 前缀后转发给 Node.js
proxy_pass http://127.0.0.1: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;
# WebSocket 支持(如果需要)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# --- 错误页面 ---
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
# --- HTTP 强制跳转 HTTPS ---
server {
listen 80;
server_name your-domain.com;
return 301 https://$server_name$request_uri;
}
2. 关键配置说明
| 配置项 | 作用 |
|---|---|
proxy_pass http://127.0.0.1:3000/; |
将 /api/ 开头的请求转发到本地 Node.js。注意末尾斜杠:如果有斜杠,Nginx 会去掉 /api 再转发;如果没有,则原样转发。建议根据 Node.js 路由设计调整。 |
proxy_set_header X-Real-IP |
让 Node.js 能获取用户真实 IP,用于日志记录或风控。 |
expires 30d |
静态资源缓存,大幅减少服务器带宽和响应时间。 |
return 301 https://... |
强制所有 HTTP 请求跳转到 HTTPS,符合小程序安全要求。 |
四、 小程序端对接要点
-
域名备案:
- 小程序后台只能配置已备案的域名。
- 确保你的云服务器已完成 ICP 备案(阿里云/腾讯云控制台可操作)。
- 域名需加入小程序“服务器域名”白名单(request 合法域名)。
-
HTTPS 必须:
- 小程序强制要求 HTTPS,且不支持自签名证书。
- 推荐使用 Let’s Encrypt(免费)或云厂商提供的免费 DV 证书。
-
请求路径一致性:
- 小程序发起请求:
https://your-domain.com/api/login - Nginx 匹配
/api/→ 转发至http://127.0.0.1:3000/login - Node.js 路由定义:
app.post('/login', ...) - 务必保持路径映射一致。
- 小程序发起请求:
五、 常见问题与排查
1. 404 Not Found
- 检查 Nginx
location /api/中的proxy_pass是否写对。 - 检查 Node.js 服务是否正在运行:
curl http://127.0.0.1:3000/api/test - 检查 Nginx 错误日志:
tail -f /var/log/nginx/error.log
2. 跨域问题(CORS)
- 由于 Nginx 做了反向X_X,浏览器实际请求的是同源域名,一般不会出现跨域问题。
- 但如果 Node.js 本身也设置了 CORS 头,可能导致双重头冲突。建议在 Nginx 层统一处理,Node.js 层可不设 CORS。
3. 静态资源加载失败
- 检查
root目录是否正确。 - 检查文件权限:
chown -R www-data:www-data /usr/share/nginx/html(Ubuntu/Debian)或nginx:nginx(CentOS)。
4. 微信开发者工具报错“不在以下 request 合法域名列表中”
- 确认域名已备案。
- 确认域名已添加到小程序后台的“开发设置”->“服务器域名”。
- 确保证书有效且未过期。
六、 安全加固建议
-
防火墙限制:
- 在云厂商控制台的安全组中,仅开放
80和443端口。 - 严禁 开放
3000(Node.js 端口)给公网。
- 在云厂商控制台的安全组中,仅开放
-
DDoS 防护:
- 对于高流量场景,建议启用云厂商的 CDN + WAF 服务,Nginx 作为源站。
-
日志审计:
- 开启 Nginx access log,定期分析异常请求。
- 使用 PM2 日志轮转,避免磁盘占满。
-
最小权限原则:
- Node.js 应用不以 root 用户运行。
- 数据库连接使用独立账号,限制远程访问。
通过以上配置,你可以构建一个高性能、安全、易于维护的小程序后端服务。Nginx 处理并发和静态资源,Node.js 专注业务逻辑,两者分工明确,是当前国内云环境下的主流方案。
CLOUD云枢