温馨提示×

Debian Nginx如何使用SSL证书

小樊
54
2025-07-28 15:53:36
栏目: 云计算

在Debian系统上使用Nginx配置SSL证书,可以按照以下步骤进行:

1. 获取SSL证书

首先,你需要一个SSL证书。你可以从Let’s Encrypt免费获取,或者从其他证书颁发机构购买。

使用Let’s Encrypt获取证书

  1. 安装Certbot:

    sudo apt update
    sudo apt install certbot python3-certbot-nginx
    
  2. 运行Certbot获取证书:

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

    按照提示完成证书的申请和安装。

2. 配置Nginx使用SSL证书

Certbot会自动修改你的Nginx配置文件,通常位于/etc/nginx/sites-available/yourdomain.com

手动配置Nginx

如果你选择手动配置,可以按照以下步骤进行:

  1. 编辑Nginx配置文件:

    sudo nano /etc/nginx/sites-available/yourdomain.com
    
  2. 添加或修改以下配置:

    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 /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
    
        root /var/www/html;
        index index.html index.htm;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        }
    
        location ~ /\.ht {
            deny all;
        }
    }
    
  3. 启用配置:

    sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
    
  4. 测试Nginx配置:

    sudo nginx -t
    
  5. 重新加载Nginx:

    sudo systemctl reload nginx
    

3. 自动续期证书

Let’s Encrypt证书通常有效期为90天,因此需要设置自动续期。

  1. 编辑Certbot的续期配置:

    sudo crontab -e
    
  2. 添加以下行以每天检查证书续期:

    0 */12 * * * certbot renew --post-hook "systemctl reload nginx"
    

4. 验证SSL配置

你可以使用以下命令验证SSL配置是否正确:

sudo openssl s_client -connect yourdomain.com:443 -servername yourdomain.com

如果一切正常,你应该会看到SSL握手成功的信息。

通过以上步骤,你就可以在Debian系统上成功配置Nginx使用SSL证书了。

0