在测试前需准备好SSL证书,可选择自签名证书(仅用于开发/内网)或Let’s Encrypt免费证书(推荐生产环境)。
nginx-selfsigned.key)和自签名证书(nginx-selfsigned.crt):sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/ssl/private/nginx-selfsigned.key \
-out /etc/ssl/certs/nginx-selfsigned.crt
命令会提示输入国家、组织等信息,均可随意填写。sudo apt update && sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Certbot会自动配置Nginx并设置证书自动续期。编辑Nginx配置文件(通常位于/etc/nginx/sites-available/default或/etc/nginx/sites-available/yourdomain.conf),添加以下内容:
# HTTP重定向到HTTPS
server {
listen 80;
server_name yourdomain.com www.yourdomain.com; # 替换为你的域名或IP
return 301 https://$host$request_uri;
}
# HTTPS配置
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
# 证书路径(自签名证书替换为上述生成的路径)
ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;
# 强化SSL配置(可选但推荐)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# 网站根目录(根据实际情况调整)
location / {
root /var/www/html;
index index.html index.htm;
}
}
保存配置文件。
在重新加载Nginx前,必须验证配置文件语法是否正确,避免因配置错误导致服务中断:
sudo nginx -t
若输出nginx: configuration file /etc/nginx/nginx.conf test is successful,则表示配置正确。
配置语法正确后,重新加载Nginx以应用更改:
sudo systemctl reload nginx
若需重启Nginx(如修改了配置但未生效),可使用:
sudo systemctl restart nginx
https://yourdomain.com(或服务器IP),若配置正确,会看到浏览器地址栏显示安全锁图标(自签名证书会提示“不安全”,但可忽略继续访问)。curl查看SSL握手详情:curl -v https://yourdomain.com
输出中会显示SSL connection using TLSv1.3(表示TLS协议生效)及证书信息。使用SSL Labs在线工具(https://www.ssllabs.com/ssltest/)输入你的域名,可全面检测SSL配置的安全性,包括:
.crt)与私钥(.key)路径正确且为配对文件,可使用openssl x509 -in cert.crt -text -noout和openssl rsa -in key.key -check验证文件完整性;sudo ufw allow 443/tcp);nginx -t报错,根据提示定位配置文件中的错误行(如路径拼写错误、缺少分号等)。