Linux服务器HTTPS(SSL/TLS)配置完全指南
在当今互联网环境中,HTTPS已成为网站安全的基本要求。本文将详细介绍如何在Linux服务器上配置HTTPS(SSL/TLS)证书,涵盖从证书申请到Nginx/Apache配置的全过程。
一、准备工作
在开始配置HTTPS前,请确保您已拥有:
- 已注册的域名
- 可正常访问的Linux服务器
- 服务器管理权限(root或sudo权限)
推荐环境:Ubuntu 20.04 LTS/CentOS 7+,Nginx 1.18+/Apache 2.4+
二、获取SSL证书的三种方式
1. 使用Let's Encrypt免费证书
Let's Encrypt是目前最流行的免费证书颁发机构:
# 安装Certbot工具
sudo apt install certbot python3-certbot-nginx # Ubuntu/Debian
sudo yum install certbot python3-certbot-nginx # CentOS/RHEL
# 获取证书
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
2. 商业SSL证书安装
购买商业证书后,通常会获得:
- 证书文件(.crt或.pem)
- 私钥文件(.key)
- 中间证书链文件
3. 自签名证书(仅测试使用)
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/ssl/private/nginx-selfsigned.key \
-out /etc/ssl/certs/nginx-selfsigned.crt
三、Nginx服务器配置HTTPS
编辑Nginx配置文件(通常位于/etc/nginx/sites-available/yourdomain.conf):
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your/private.key;
# 启用TLS 1.2/1.3
ssl_protocols TLSv1.2 TLSv1.3;
# 优化加密套件
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
# 其他配置...
}
配置完成后记得测试并重载Nginx:
sudo nginx -t
sudo systemctl reload nginx
四、Apache服务器配置HTTPS
编辑Apache配置文件(通常位于/etc/apache2/sites-available/yourdomain.conf):
ServerName yourdomain.com
ServerAlias www.yourdomain.com
SSLEngine on
SSLCertificateFile /path/to/your/certificate.crt
SSLCertificateKeyFile /path/to/your/private.key
SSLCertificateChainFile /path/to/chainfile.crt
# 其他配置...
启用SSL模块并重启Apache:
sudo a2enmod ssl
sudo systemctl restart apache2
五、进阶配置与优化
1. HTTP强制跳转HTTPS
Nginx配置:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$server_name$request_uri;
}
2. 启用HSTS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
3. 证书自动续期(Let's Encrypt)
# 测试续期
sudo certbot renew --dry-run
# 添加定时任务(crontab -e)
0 0 */60 * * certbot renew --quiet
通过以上步骤,您的Linux服务器已成功配置HTTPS。定期检查证书有效期并保持服务器软件更新,可确保网站长期安全运行。建议使用SSL Labs测试工具验证配置安全性。
