温馨提示×

Debian Nginx 配置 HTTPS 有哪些步骤

小樊
41
2026-01-08 09:03:45
栏目: 智能运维

在 Debian 系统上配置 Nginx 以支持 HTTPS 主要涉及以下几个步骤:

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

    sudo apt update
    sudo apt install nginx
    
  2. 获取 SSL 证书: 你可以从 Let’s Encrypt 获取免费的 SSL 证书。使用 Certbot 是一个简单的方法:

    sudo apt install certbot python3-certbot-nginx
    sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
    

    在提示时,Certbot 会自动配置 Nginx 并重载服务。

  3. 手动配置 SSL(如果你不使用 Certbot):

    • 创建一个新的 Nginx 服务器块文件,例如 /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;
          }
      }
      
    • 创建 SSL 目录并启用站点:

      sudo mkdir /var/www/certbot
      sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
      sudo nginx -t  # 检查配置文件是否有误
      sudo systemctl reload nginx
      
    • 使用 Certbot 获取证书:

      sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
      
  4. 配置 Nginx 以使用 SSL: 编辑你的 Nginx 服务器块文件(例如 /etc/nginx/sites-available/yourdomain.com),添加或修改以下内容:

    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;
        }
    
        # 其他配置...
    }
    
  5. 重载 Nginx: 保存配置文件后,重载 Nginx 以应用更改:

    sudo systemctl reload nginx
    
  6. 测试配置: 确保 Nginx 正确配置并能够通过 HTTPS 访问:

    sudo nginx -t
    
  7. 自动续期证书: Certbot 会自动设置一个 cron 任务或 systemd 定时器来自动续期证书。你可以手动测试续期过程:

    sudo certbot renew --dry-run
    

通过以上步骤,你应该能够在 Debian 系统上成功配置 Nginx 以支持 HTTPS。

0