如何配置SSL证书实现全站加密?
全站SSL配置,照着做就行
第一步:拿到证书
两条路:
免费:Let's Encrypt,用certbot一键拉,90天自动续期,够用了。
付费:阿里云/腾讯云买,适合需要通配符证书(*.yourdomain.com)或者要备案的场景。
拿到手就是两个文件:.crt(公钥证书)和 .key(私钥),放服务器上,权限设成600,别让别人读到私钥。
第二步:Nginx 配置(最常见)
nginx
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /path/to/yourdomain.crt;
ssl_certificate_key /path/to/yourdomain.key;
# 推荐的安全配置,直接抄
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 你的站点配置
root /var/www/html;
index index.html;}
HTTP强制跳HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$server_name$request_uri;}
改完 nginx -t 检查语法,没报错就 systemctl reload nginx。
第三步:全站强制HTTPS
光Nginx跳转还不够,得在应用层也堵住HTTP的口。
方式一:Nginx加Header
nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
这行的意思是:浏览器记住一年内只用HTTPS访问这个域名,包括子域名。
方式二:代码层重定向
以Node.js为例:
js
app.use((req, res, next) => {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(`https://${req.hostname}${req.url}`);}
next();
});
几个容易踩的坑
问题 原因 解决
混合内容警告 页面里引用了http://的资源 全站搜索替换成https://或//协议相对路径
证书不信任 没用CA签发的证书,自己签的 生产环境别用自签名,浏览器会拦
续期失败 certbot cron没跑或者防火墙挡了80端口 检查certbot renew --dry-run
配置完用
SSL Labs
测一下,拿到A或A+就算过关了。