如何在Ubuntu上配置SSL加密
小樊
38
2025-11-15 15:15:39
在 Ubuntu 上配置 SSL 加密
一 准备与前置条件
- 准备一个可解析到服务器的域名,并在云厂商或防火墙开放 TCP 80/443 端口。
- 安装基础工具:更新索引并安装 OpenSSL 与所选 Web 服务器(如 Nginx/Apache)。
- 示例:sudo apt update && sudo apt install -y openssl nginx
二 获取 SSL 证书
- 方案 A(推荐)使用 Let’s Encrypt + Certbot 自动获取并部署
- 安装 Certbot 及对应插件:
- Nginx:sudo apt install -y certbot python3-certbot-nginx
- Apache:sudo apt install -y certbot python3-certbot-apache
- 获取并自动配置:
- Nginx:sudo certbot --nginx -d example.com -d www.example.com
- Apache:sudo certbot --apache -d example.com -d www.example.com
- 证书默认路径:/etc/letsencrypt/live/example.com/,常用文件为 fullchain.pem(证书链)与 privkey.pem(私钥)。证书有效期 90 天,Certbot 可自动续期。
- 方案 B 使用 自签名证书(测试/内网)
- 生成私钥与自签名证书(有效期 365 天):
- openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
- 将证书与私钥部署到安全目录(如 /etc/ssl/private/ 与 /etc/ssl/certs/),后续在 Web 服务器中指定路径即可。
三 配置 Web 服务器启用 HTTPS
- Nginx 示例(同时强制 HTTP→HTTPS)
- 建议生成 DH 参数(提升安全性):sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
- 配置片段:
- server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; }
- server { listen 443 ssl; 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_dhparam /etc/ssl/certs/dhparam.pem;
- ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on;
- root /var/www/html; index index.html;
- location / { try_files $uri $uri/ =404; } }
- 检查并重载:sudo nginx -t && sudo systemctl reload nginx
- Apache 示例(手动配置)
- 启用模块与站点:sudo a2enmod ssl && sudo a2ensite default-ssl && sudo systemctl restart apache2
- 配置片段(VirtualHost *:443):
- SSLEngine on
- SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
- SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
- SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
- 可按需添加:SSLProtocol TLSv1.2 TLSv1.3; SSLCipherSuite HIGH:!aNULL:!MD5; SSLHonorCipherOrder on
四 验证与自动续期
- 配置验证
- 在线检测:使用 SSL Labs SSL Server Test 评估安全等级与兼容性。
- 命令行快速检查:
- 查看握手与证书链:openssl s_client -connect example.com:443 -servername example.com
- 查看证书信息:echo | openssl s_client -connect example.com:443 2>/dev/null | openssl x509 -noout -subject -issuer -dates
- 自动续期
- 使用 systemd 定时器(推荐):sudo systemctl enable --now certbot.timer(Certbot 安装后通常已自带)
- 或添加定时任务(示例:每两月检查一次):0 0 1 */2 * /usr/bin/certbot renew --quiet && systemctl reload nginx
五 常见问题与优化
- 证书路径与权限:确保 fullchain.pem 与 privkey.pem 路径正确,私钥仅对必要服务可读(如 chmod 600)。
- 强加密与协议:仅启用 TLSv1.2/1.3,禁用 SSLv3/TLSv1.0/1.1;优先使用 ECDHE 等前向保密套件。
- 完整链与中间证书:Nginx 使用 fullchain.pem;Apache 可同时配置 SSLCertificateFile 与 SSLCertificateChainFile。
- 性能与安全:启用 DH 参数 与 OCSP Stapling(按需);为静态资源启用长缓存与 HSTS(在确认全站 HTTPS 后再启用)。
- 防火墙与云安全组:放行 80/443,避免 CDN/反向代理与源站协议不一致导致重定向或证书不匹配。