Nginx 反向代理 + acme.sh:给云服务器上的多个服务自动配 HTTPS
【摘要】 在一台云服务器上同时跑博客、API 和监控面板很常见。本文用 Nginx 做统一入口,用 acme.sh 申请并自动续期 Let’s Encrypt 证书,实现多个子域名全部走 HTTPS。 一、准备一台 Linux 云服务器(本文以 Huawei Cloud EulerOS / CentOS 系为例),安全组放通 80、443 端口。域名解析:blog.example.com、api.ex...
在一台云服务器上同时跑博客、API 和监控面板很常见。本文用 Nginx 做统一入口,用 acme.sh 申请并自动续期 Let’s Encrypt 证书,实现多个子域名全部走 HTTPS。
一、准备
- 一台 Linux 云服务器(本文以 Huawei Cloud EulerOS / CentOS 系为例),安全组放通 80、443 端口。
- 域名解析:
blog.example.com、api.example.com都指向服务器公网 IP。 - 后端服务:博客监听 127.0.0.1:3000,API 监听 127.0.0.1:8080。
二、安装 Nginx 与 acme.sh
yum install -y nginx
systemctl enable --now nginx
curl https://get.acme.sh | sh -s email=me@example.com
source ~/.bashrc
三、先配 HTTP 站点用于验证
server {
listen 80;
server_name blog.example.com api.example.com;
location /.well-known/acme-challenge/ { root /var/www/acme; }
location / { return 301 https://$host$request_uri; }
}
mkdir -p /var/www/acme && nginx -t && systemctl reload nginx
四、申请并安装证书
acme.sh --issue -d blog.example.com -d api.example.com -w /var/www/acme
mkdir -p /etc/nginx/ssl
acme.sh --install-cert -d blog.example.com \
--key-file /etc/nginx/ssl/site.key \
--fullchain-file /etc/nginx/ssl/site.crt \
--reloadcmd "systemctl reload nginx"
--reloadcmd 会被记录下来,acme.sh 自带的定时任务每 60 天续期后会自动重载 Nginx,不用人工干预。
五、HTTPS 反向代理配置
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
server {
listen 443 ssl http2;
server_name blog.example.com;
ssl_certificate /etc/nginx/ssl/site.crt;
ssl_certificate_key /etc/nginx/ssl/site.key;
ssl_protocols TLSv1.2 TLSv1.3;
location / {
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 https;
}
}
server {
listen 443 ssl http2;
server_name api.example.com;
ssl_certificate /etc/nginx/ssl/site.crt;
ssl_certificate_key /etc/nginx/ssl/site.key;
client_max_body_size 20m;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_read_timeout 300s;
}
}
API 站点额外开启了 WebSocket 升级和更长的读超时,适合有长连接的服务。
六、验证与排错
nginx -t && systemctl reload nginx
curl -I https://blog.example.com
acme.sh --list # 查看证书与到期时间
acme.sh --cron --force # 手动演练一次续期
常见问题:
- 申请失败提示 timeout:检查安全组 80 端口和域名解析是否生效。
- 502 Bad Gateway:后端没起来,或 SELinux 拦截,可执行
setsebool -P httpd_can_network_connect 1。 - 浏览器提示证书不匹配:确认申请时用
-d包含了全部子域名。
总结
Nginx 统一入口 + acme.sh 自动续期,一次配置后证书再也不会过期,新增服务只需加一个 server 块。后端服务只监听 127.0.0.1,也顺带减少了暴露面。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)