在 Linux 上使用 Nginx 配置 SSL(HTTPS) 通常包含以下几个步骤:申请/生成证书、配置 Nginx、重启并验证。下面以 自签名证书 和 Let’s Encrypt 免费证书 两种方式说明。
确保已安装 Nginx:
nginx -v
如未安装:
# Ubuntu / Debian
sudo apt update
sudo apt install nginx
# CentOS
sudo yum install nginx
sudo mkdir -p /etc/nginx/ssl
cd /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout example.com.key \
-out example.com.crt
按提示填写信息(Common Name 填域名或 IP)。
编辑站点配置:
sudo vim /etc/nginx/conf.d/ssl.conf
示例配置:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
sudo nginx -t
sudo systemctl restart nginx
访问:
https://example.com
(浏览器会提示不安全,属正常现象)
# Ubuntu
sudo apt install certbot python3-certbot-nginx
# CentOS
sudo yum install epel-release
sudo yum install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
按提示操作,Certbot 会自动:
sudo certbot renew --dry-run
Certbot 通常已配置 systemd 定时任务。
add_header Strict-Transport-Security "max-age=31536000" always;
ssl_protocols TLSv1.2 TLSv1.3;
确保放行 80 和 443:
sudo ufw allow 80
sudo ufw allow 443
如果你有 具体域名、系统版本(Ubuntu/CentOS)或反向代理需求(如 Node、Java),我可以给你更精确的配置示例。