如何自托管生产环境Next.js应用并通过HTTPS对外提供服务?
用自有SSL证书部署Next.js应用(GoDaddy域名、无Docker/云托管)
1. 配置子域名解析到服务器IP
- 登录GoDaddy域名管理后台,找到你的主域名
- 添加一条A记录:
- 主机名填目标子域名(比如
dashboard) - 指向值填写你的虚拟服务器公网IP
- 主机名填目标子域名(比如
- 等待解析生效(通常10-30分钟),可通过命令验证:
nslookup dashboard.yourdomain.com,返回IP需与服务器公网IP一致
2. 获取/准备SSL证书
方案A:免费Let's Encrypt证书
- 在服务器安装certbot:
- Debian/Ubuntu:
apt update && apt install certbot - CentOS/RHEL:
yum install certbot
- Debian/Ubuntu:
- 生成证书:
certbot certonly --standalone -d dashboard.yourdomain.com- 按提示输入邮箱、同意条款,证书会自动生成在
/etc/letsencrypt/live/dashboard.yourdomain.com/目录,包含fullchain.pem(证书链)和privkey.pem(私钥)
- 按提示输入邮箱、同意条款,证书会自动生成在
方案B:GoDaddy付费自有证书
- 在服务器生成CSR文件:
openssl req -new -newkey rsa:2048 -nodes -keyout dashboard.key -out dashboard.csr - 登录GoDaddy证书管理页面,提交CSR获取证书,下载后将证书文件(通常为
.crt/.pem)和私钥文件(dashboard.key)分别放到服务器/etc/ssl/certs/和/etc/ssl/private/目录
3. 构建并启动Next.js应用
- 在服务器拉取代码,或上传本地构建好的文件
- 安装依赖并构建:
npm install && npm run build,生成.next文件夹 - 用pm2管理后台进程:
- 安装pm2:
npm install -g pm2 - 启动应用:
pm2 start npm --name "next-dashboard" -- start - 验证运行状态:
pm2 list,确认next-dashboard状态为online,默认监听端口3000
- 安装pm2:
4. 配置Nginx反向代理处理HTTPS
- 安装Nginx:
- Debian/Ubuntu:
apt install nginx - CentOS/RHEL:
yum install nginx
- Debian/Ubuntu:
- 创建站点配置文件:
nano /etc/nginx/sites-available/dashboard.yourdomain.com - 粘贴以下配置(根据证书类型替换路径):
server { listen 80; server_name dashboard.yourdomain.com; # 强制HTTP跳转HTTPS return 301 https://$host$request_uri; } server { listen 443 ssl; server_name dashboard.yourdomain.com; # Let's Encrypt证书路径 ssl_certificate /etc/letsencrypt/live/dashboard.yourdomain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/dashboard.yourdomain.com/privkey.pem; # GoDaddy证书替换为以下路径 # ssl_certificate /etc/ssl/certs/your-dashboard-cert.pem; # ssl_certificate_key /etc/ssl/private/dashboard.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; 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; } } - 启用配置并重启Nginx:
ln -s /etc/nginx/sites-available/dashboard.yourdomain.com /etc/nginx/sites-enabled/ nginx -t # 检查配置语法 systemctl restart nginx
5. 开放防火墙端口
- Debian/Ubuntu(ufw):
ufw allow 80/tcp ufw allow 443/tcp ufw reload - CentOS/RHEL(firewalld):
firewall-cmd --add-service=http --permanent firewall-cmd --add-service=https --permanent firewall-cmd --reload - 同时确保虚拟服务器提供商的安全组规则开放80、443端口
6. 验证部署
访问https://dashboard.yourdomain.com,浏览器地址栏显示安全锁且能正常加载应用即可。
内容的提问来源于stack exchange,提问作者Bogdan B
相关产品推荐
相关产品推荐

