sudo yum update -y
sudo yum install -y epel-release
sudo yum install -y nginx openssl
sudo systemctl start nginx
sudo systemctl enable nginx
SSL证书是HTTPS的核心,可选择自签名证书(测试用)或正式证书(生产用)。
自签名证书由本地生成,浏览器会提示“不安全”,但可用于本地开发环境。
sudo mkdir -p /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/nginx/ssl/selfsigned.key \
-out /etc/nginx/ssl/selfsigned.crt \
-subj "/CN=yourdomain.com" # 替换为你的域名或服务器IP
说明:
-nodes:不加密私钥(方便后续配置);-days 365:证书有效期1年;-newkey rsa:2048:生成2048位的RSA私钥。使用Let’s Encrypt免费获取正式证书(支持自动续期),需通过certbot工具实现。
sudo yum install -y certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com # 替换为你的域名
说明:
certbot会自动验证域名所有权(通过HTTP或DNS),并配置Nginx的SSL参数;/etc/letsencrypt/live/yourdomain.com/,包含fullchain.pem(证书链)和privkey.pem(私钥)。编辑Nginx配置文件(推荐使用/etc/nginx/conf.d/ssl.conf,避免修改主配置文件),添加以下内容:
sudo vim /etc/nginx/conf.d/redirect.conf
内容:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com; # 替换为你的域名
return 301 https://$host$request_uri; # 将所有HTTP请求重定向到HTTPS
}
sudo vim /etc/nginx/conf.d/ssl.conf
内容(自签名证书示例):
server {
listen 443 ssl http2; # 启用HTTPS和HTTP/2(提升性能)
server_name yourdomain.com www.yourdomain.com;
# SSL证书路径(根据证书类型调整)
ssl_certificate /etc/nginx/ssl/selfsigned.crt; # 自签名证书路径
ssl_certificate_key /etc/nginx/ssl/selfsigned.key; # 私钥路径
# 推荐的安全配置(强化SSL加密)
ssl_protocols TLSv1.2 TLSv1.3; # 仅使用TLS 1.2及以上版本(禁用SSLv3、TLS 1.0/1.1)
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 /usr/share/nginx/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404; # 处理静态文件请求
}
}
说明:
ssl_certificate和ssl_certificate_key路径替换为/etc/letsencrypt/live/yourdomain.com/fullchain.pem和/etc/letsencrypt/live/yourdomain.com/privkey.pem;http2:启用HTTP/2协议,提升网页加载速度(需Nginx版本≥1.9.5)。sudo nginx -t
若输出nginx: configuration file /etc/nginx/nginx.conf test is successful,则表示配置正确。sudo systemctl reload nginx
https://yourdomain.com,若看到锁图标(表示连接安全),则说明配置成功。curl命令检查HTTPS响应头(忽略证书验证)。curl -kIv https://yourdomain.com
若输出中包含HTTP/2 200和SSL Connection: Secure,则表示SSL配置生效。sudo firewall-cmd --permanent --add-port={80/tcp,443/tcp}
sudo firewall-cmd --reload
Enforcing模式,需允许Nginx访问网络。sudo setsebool -P httpd_can_network_connect 1
若使用Let’s Encrypt证书,certbot会自动添加续期任务(每天检查),但需手动触发重载Nginx。
sudo certbot renew --dry-run # 测试续期(模拟操作)
sudo systemctl reload nginx # 续期后重载Nginx
通过以上步骤,即可在CentOS上为Nginx配置SSL加密,实现HTTPS安全访问。生产环境建议使用Let’s Encrypt等免费正式证书,提升用户信任度。