温馨提示×

linux nginx如何设置ssl

小樊
64
2026-10-29 06:50:28
栏目: 云计算

在 Linux 上使用 Nginx 配置 SSL(通常是 HTTPS),一般分为以下几个步骤:获取证书 → 安装 Nginx → 配置 SSL → 重启并验证。下面以最常见的 Let’s Encrypt 免费证书 和 自签名证书 两种方式说明。


一、使用 Let’s Encrypt 免费 SSL(推荐,生产环境)

1. 安装 Nginx

# Ubuntu / Debian
sudo apt update
sudo apt install nginx -y

# CentOS / Rocky / Alma
sudo yum install nginx -y
sudo systemctl enable --now nginx

2. 安装 Certbot

# 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

3. 申请并自动配置 SSL

sudo certbot --nginx -d example.com -d www.example.com
  • 按提示输入邮箱
  • 同意条款
  • 选择是否重定向 HTTP → HTTPS(建议选 2)

Certbot 会自动修改 Nginx 配置并启用 HTTPS。

4. 验证自动续期

sudo certbot renew --dry-run

二、使用自签名证书(测试环境)

1. 生成私钥和证书

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)。

2. 配置 Nginx SSL

编辑站点配置:

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;
}

3. 测试并重载 Nginx

sudo nginx -t
sudo systemctl reload nginx

三、通用 SSL 安全配置(推荐)

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)、域名情况 或 已有证书文件,我可以给你更精确的配置。

0 踩