温馨提示×

linux nginx怎么配置ssl

小樊
37
2026-10-29 03:25:21
栏目: 云计算

在 Linux 上使用 Nginx 配置 SSL(HTTPS) 一般分为以下几个步骤,以 Let’s Encrypt 免费证书 和 自签证书 两种方式说明,你可以按需要选择。


一、准备工作

  1. 一台 Linux 服务器(CentOS / Ubuntu / Debian 均可)
  2. 已安装 Nginx
  3. 一个域名(公网证书需要,自签可不需要)
  4. 域名已解析到服务器 IP

查看 Nginx 是否安装:

nginx -v

二、使用 Let’s Encrypt 免费 SSL(推荐)

1. 安装 certbot

Ubuntu / Debian

sudo apt update
sudo apt install certbot python3-certbot-nginx -y

CentOS

sudo yum install epel-release -y
sudo yum install certbot python3-certbot-nginx -y

2. 自动申请并配置 SSL

sudo certbot --nginx -d www.example.com -d example.com

按提示选择:

  • 是否重定向 HTTP → HTTPS(建议选 2)

3. 自动续期测试

sudo certbot renew --dry-run

✅ 证书位置:

/etc/letsencrypt/live/example.com/

三、手动配置 Nginx SSL(已有证书)

1. 上传证书文件

通常包括:

  • example.com.crt(证书)
  • example.com.key(私钥)

放到:

/etc/nginx/ssl/

2. 修改 Nginx 配置

编辑站点配置:

sudo vim /etc/nginx/conf.d/example.conf

示例配置:

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com www.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;

    root /usr/share/nginx/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

3. 检查并重启 Nginx

sudo nginx -t
sudo systemctl restart nginx

四、自签 SSL 证书(测试用)

sudo openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout /etc/nginx/ssl/self.key \
-out /etc/nginx/ssl/self.crt

然后按「三、手动配置」使用即可(浏览器会提示不安全)。


五、常见问题

✅ 防火墙

sudo ufw allow 80,443/tcp

✅ HTTPS 无法访问

  • 检查 443 端口是否开放
  • 检查证书路径是否正确
  • 查看错误日志:
tail -f /var/log/nginx/error.log

如果你愿意,可以告诉我:

  • 使用的 Linux 发行版
  • 是否已有证书
  • 单域名 / 多域名 / 泛域名

我可以直接帮你写 完整 Nginx 配置。

0 踩