温馨提示×

Nginx在Debian中如何设置SSL证书

小樊
52
2025-09-24 17:02:27
栏目: 云计算

在Debian系统中设置Nginx的SSL证书,可以按照以下步骤进行:

1. 安装Nginx

如果你还没有安装Nginx,可以使用以下命令进行安装:

sudo apt update
sudo apt install nginx

2. 获取SSL证书

你可以从Let’s Encrypt免费获取SSL证书。使用Certbot工具可以简化这个过程。

安装Certbot

sudo apt install certbot python3-certbot-nginx

获取并安装证书

运行以下命令来获取并安装证书:

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

yourdomain.comwww.yourdomain.com替换为你的域名。

Certbot会自动配置Nginx并重启服务。它会提示你输入邮箱地址、同意服务条款,并选择是否设置自动续期。

3. 手动配置SSL证书

如果你不想使用Certbot,也可以手动配置SSL证书。

获取SSL证书

你可以从Let’s Encrypt或其他证书颁发机构获取SSL证书。通常你需要以下文件:

  • yourdomain.com.crt(证书文件)
  • yourdomain.com.key(私钥文件)
  • ca_bundle.crt(CA证书文件,如果需要)

配置Nginx

编辑Nginx配置文件,通常位于/etc/nginx/sites-available/yourdomain.com

sudo nano /etc/nginx/sites-available/yourdomain.com

添加或修改以下配置:

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name yourdomain.com www.yourdomain.com;

    ssl_certificate /path/to/yourdomain.com.crt;
    ssl_certificate_key /path/to/yourdomain.com.key;
    ssl_trusted_certificate /path/to/ca_bundle.crt; # 如果需要

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;

    root /var/www/html;
    index index.html index.htm;

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

/path/to/yourdomain.com.crt/path/to/yourdomain.com.key/path/to/ca_bundle.crt替换为实际的文件路径。

启用配置

创建一个符号链接以启用配置:

sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/

测试配置并重启Nginx

sudo nginx -t
sudo systemctl restart nginx

4. 自动续期

如果你使用Certbot获取证书,它会自动设置一个cron任务来定期续期证书。你可以手动测试续期过程:

sudo certbot renew --dry-run

如果没有问题,Certbot会自动续期证书。

通过以上步骤,你可以在Debian系统中成功设置Nginx的SSL证书。

0