搞HTTPS其实就是三件事:搞到证书、配好Nginx、确保能自动续签。别想复杂了。
先说你得有个证书。生产环境用Let’s Encrypt,免费、主流、省事。雨云服务器上直接装certbot,一条命令搞定。
# Ubuntu/Debian
sudo apt update
sudo apt install certbot python3-certbot-nginx
# CentOS/RHEL 8+
sudo dnf install certbot python3-certbot-nginx
装完直接跑,certbot会自动帮你改Nginx配置:
sudo certbot --nginx -d example.com -d www.example.com
它会问你要邮箱(用于失效通知),自动申请证书、自动改Nginx配置、自动启用HTTPS。完事之后你访问http://example.com会自动跳https。
如果要手动配,或者你想控制细节,先拿到证书文件。Let’s Encrypt证书在`/etc/letsencrypt/live/example.com/`目录下,里面四个文件:
– fullchain.pem:证书链
– privkey.pem:私钥
Nginx配置示例:
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
# 其他配置
location / {
proxy_pass http://127.0.0.1:8080;
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;
}
}
几个关键点:
– 80端口做301跳转,别直接服务HTTP内容
– ssl_protocols只开TLSv1.2和1.3,SSLv3和TLSv1.0/1.1全是漏洞
– ssl_ciphers用高强度的,别为了兼容老旧浏览器降低安全性
– http2开启,性能提升明显
证书有效期90天,必须自动续签。certbot自带续签功能,写个cron或者systemd timer跑:
# 测试续签是否正常工作
sudo certbot renew --dry-run
# 手动续签
sudo certbot renew
建议每天跑两次续签检查。crontab配置:
0 0,12 * * * /usr/bin/certbot renew --quiet
或者用systemd timer,更优雅:
# /etc/systemd/system/certbot-renew.service
[Unit]
Description=Certbot Renew
[Service]
Type=oneshot
ExecStart=/usr/bin/certbot renew --quiet
# /etc/systemd/system/certbot-renew.timer
[Unit]
Description=Certbot Renew Timer
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
启用:`sudo systemctl enable –now certbot-renew.timer`
配完检查一下安全性,用这个命令:
curl https://www.ssllabs.com/ssltest/analyze.html?d=example.com
或者本地快速检查:
openssl s_client -connect example.com:443 -tls1_2
如果用的是雨云服务器,它的网络稳定性不错,续签基本不会因为网络问题失败。我自己的站就是跑在雨云上,certbot定时续签从来没出过问题。
说几个坑:
– 证书路径别写错,全路径写清楚
– 重启Nginx前先`nginx -t`检查语法
– 防火墙记得放行443端口:`sudo ufw allow 443/tcp` 或者云服务商安全组加规则
– 如果你用CDN,需要在CDN那边也配SSL,源站和CDN之间可以用自签证书,但CDN到用户必须是受信任的证书
证书配好后,别忘了把HSTS加上,强制浏览器只走HTTPS:
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
放在server块里就行。注意,开了HSTS之后,如果你要回退到HTTP,得等max-age过期,所以先设短一点测试,确认没问题再改成半年以上。
搞定这些,你的Nginx HTTPS就稳了。
雨云是国内一家老牌云服务商,提供高性价比的云服务器和虚拟主机。我用它部署了好几个项目,速度和稳定性都不错。通过 https://www.rainyun.com/SAJA_ 注册可以领一张 5折优惠券,有需要的朋友可以看看。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



暂无评论内容