Nginx SSL/TLS 配置指南:从安装到强化安全
前言
在现代 Web 服务中,启用 SSL/TLS 加密是保障数据传输安全的基本要求。本文将详细介绍如何在 Nginx 中配置 SSL/TLS,包括证书获取、配置优化与安全性强化,适合从入门到进阶的用户阅读。
1. 安装 Nginx
如果你还没有安装 Nginx,可以按照以下步骤进行:
1.1 安装 EPEL 仓库
sudo yum install epel-release -y
1.2 安装 Nginx
sudo yum install nginx -y
1.3 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
1.4 验证安装
访问 http://your_server_ip
,若能看到 Nginx 欢迎页,说明安装成功。若无法访问,可运行以下命令检查状态:
sudo systemctl status nginx
2. 获取 SSL/TLS 证书
2.1 使用 Let’s Encrypt 免费证书(推荐)
Let’s Encrypt 提供免费且可自动续期的 SSL 证书,适合生产环境使用。
安装 Certbot
sudo yum install epel-release -y
sudo yum install certbot python2-certbot-nginx -y
获取证书
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
请将 yourdomain.com
替换为你的实际域名。Certbot 会自动配置 Nginx 并启用 HTTPS。
配置自动续期
Let’s Encrypt 证书有效期为 90 天,建议设置定时任务自动续期:
sudo crontab -e
添加以下内容:
0 0 * * * /usr/bin/certbot renew --quiet
2.2 创建自签名证书(仅用于测试)
适用于开发或测试环境,不推荐在生产环境中使用。
生成密钥和证书
sudo mkdir -p /usr/local/nginx/ssl/{private,certs}
openssl genpkey -algorithm RSA -out /usr/local/nginx/ssl/private/nginx-selfsigned.key -pkeyopt rsa_keygen_bits:2048
openssl req -new -key /usr/local/nginx/ssl/private/nginx-selfsigned.key -out /usr/local/nginx/ssl/certs/nginx-selfsigned.csr
openssl x509 -req -days 365 -in /usr/local/nginx/ssl/certs/nginx-selfsigned.csr -signkey /usr/local/nginx/ssl/private/nginx-selfsigned.key -out /usr/local/nginx/ssl/certs/nginx-selfsigned.crt
生成过程中需填写一些基本信息,如国家、组织、域名等。
3. 配置 Nginx 启用 SSL/TLS
3.1 编辑配置文件
vim /usr/local/nginx/conf/nginx.conf
3.2 添加 SSL 配置
server {
listen 443 ssl;
server_name benet.com www.benet.com;
ssl_certificate /usr/local/nginx/ssl/certs/nginx-selfsigned.crt;
ssl_certificate_key /usr/local/nginx/ssl/private/nginx-selfsigned.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256;
ssl_prefer_server_ciphers on;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
3.3 配置 HTTP 重定向到 HTTPS
server {
listen 80;
server_name benet.com www.benet.com;
return 301 https://$host$request_uri;
}
3.4 启用 HTTP/2(可选)
server {
listen 443 ssl http2;
...
}
4. 强化 SSL/TLS 安全性
4.1 禁用弱加密协议
ssl_protocols TLSv1.2 TLSv1.3;
4.2 启用 HSTS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
4.3 生成并配置 DH 参数
sudo openssl dhparam -out /usr/local/nginx/ssl/certs/dhparam.pem 2048
在 Nginx 配置中添加:
ssl_dhparam /usr/local/nginx/ssl/certs/dhparam.pem;
4.4 配置加密套件
ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
5. 验证配置
5.1 检查语法
sudo nginx -t
5.2 重启 Nginx
sudo systemctl restart nginx
5.3 测试 HTTPS
访问 https://benet.com
,确认出现绿色锁图标。也可使用 curl
测试:
curl -I https://benet.com
6. 定期更新证书
若使用 Let’s Encrypt,证书会自动续期。若使用自签名证书,需手动更新。建议设置提醒,避免证书过期导致服务中断。