在 Linux 上使用 Nginx 配置 SSL(通常是 HTTPS),一般分为以下几个步骤:获取证书 → 安装 Nginx → 配置 SSL → 重启并验证。下面以最常见的 Let’s Encrypt 免费证书 和 自签名证书 两种方式说明。
# Ubuntu / Debian
sudo apt update
sudo apt install nginx -y
# CentOS / Rocky / Alma
sudo yum install nginx -y
sudo systemctl enable --now nginx
# Ubuntu / Debian
sudo apt install certbot python3-certbot-nginx -y
# CentOS
sudo yum install epel-release -y
sudo yum install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com
Certbot 会自动修改 Nginx 配置并启用 HTTPS。
sudo certbot renew --dry-run
sudo mkdir -p /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout /etc/nginx/ssl/nginx.key \
-out /etc/nginx/ssl/nginx.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/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
sudo nginx -t
sudo systemctl reload nginx
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# firewalld
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
# ufw
sudo ufw allow 80,443/tcp
浏览器访问:
https://example.com
或使用:
curl -I https://example.com
如果你有 具体系统(Ubuntu/CentOS)、域名情况 或 已有证书文件,我可以给你更精确的配置。