在LNMP(Linux + Nginx + MySQL + PHP)环境中安装SSL证书实现HTTPS加密的步骤如下,以Let's Encrypt免费证书为例:
firewall-cmd --add-service=https
或 ufw allow 443
)# 安装Certbot
sudo apt install certbot python3-certbot-nginx # Ubuntu/Debian
sudo yum install certbot python3-certbot-nginx # CentOS
# 自动获取并配置证书(需已配置好Nginx站点)
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
cd ~/lnmp1.x/tools
./certbot.sh
编辑Nginx站点配置文件(通常位于/usr/local/nginx/conf/vhost/yourdomain.conf
):
server {
listen 443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
# 其他配置...
}
# HTTP强制跳转HTTPS
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
# 测试Nginx配置
nginx -t
# 重载Nginx
systemctl reload nginx # 或 service nginx reload
Let's Encrypt证书有效期为90天,设置自动续期:
# 测试续期命令
certbot renew --dry-run
# 添加定时任务(每月1号凌晨3点续期)
crontab -e
添加:
0 3 1 * * /usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx"
https://yourdomain.com
检查浏览器锁标志bash
curl -I https://yourdomain.com
openssl s_client -connect yourdomain.com:443 -servername yourdomain.com
证书不生效:
nginx -t
检查配置语法混合内容警告:
HSTS配置(增强安全):
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
通过以上步骤,你的LNMP环境将成功启用HTTPS加密。如需商业证书(如DigiCert/Sectigo),只需替换证书文件路径即可。