linux

如何在 Linux 上为 Node.js 应用配置 SSL

小樊
42
2025-06-03 01:55:51
栏目: 云计算

在 Linux 上为 Node.js 应用配置 SSL 可以通过以下步骤完成。我们将使用 Let’s Encrypt 提供的免费 SSL 证书,并使用 Certbot 工具来自动化证书的申请和续期过程。

前提条件

  1. Node.js 应用:确保你的 Node.js 应用已经运行在服务器上。
  2. Nginx 或 Apache:作为反向代理服务器,处理 SSL 终端和流量转发。
  3. 域名:确保你有一个域名,并且该域名指向你的服务器 IP 地址。

步骤 1:安装 Certbot

Certbot 是一个自动化的工具,用于获取、安装和续期 Let’s Encrypt 证书。你可以使用以下命令安装 Certbot:

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

如果你使用的是 Apache,可以安装 python3-certbot-apache

sudo apt install certbot python3-certbot-apache

步骤 2:配置 Nginx 或 Apache

使用 Nginx

  1. 创建 Nginx 配置文件: 创建一个新的 Nginx 配置文件,例如 /etc/nginx/sites-available/yourdomain.com

    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 / {
            proxy_pass http://localhost:3000; # 你的 Node.js 应用监听的端口
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    
  3. 启用配置: 创建一个符号链接到 sites-enabled 目录:

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

    sudo nginx -t
    
  5. 重启 Nginx

    sudo systemctl restart nginx
    

使用 Apache

  1. 启用 SSL 模块

    sudo a2enmod ssl
    sudo systemctl restart apache2
    
  2. 创建 Apache 配置文件: 创建一个新的 Apache 配置文件,例如 /etc/apache2/sites-available/yourdomain.com.conf

    sudo nano /etc/apache2/sites-available/yourdomain.com.conf
    
  3. 添加以下内容

    <VirtualHost *:443>
        ServerName yourdomain.com www.yourdomain.com
    
        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf
    
        ProxyPass / http://localhost:3000/
        ProxyPassReverse / http://localhost:3000/
    
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    
  4. 启用配置

    sudo a2ensite yourdomain.com.conf
    
  5. 测试 Apache 配置

    sudo apache2ctl configtest
    
  6. 重启 Apache

    sudo systemctl restart apache2
    

步骤 3:获取 SSL 证书

使用 Certbot 获取 SSL 证书:

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

如果你使用的是 Apache,命令如下:

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

Certbot 会自动配置 Nginx 或 Apache,并下载 Let’s Encrypt 证书到 /etc/letsencrypt/live/yourdomain.com 目录。

步骤 4:自动续期

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

sudo certbot renew --dry-run

如果一切正常,Certbot 会自动续期证书并更新 Nginx 或 Apache 配置。

总结

通过以上步骤,你可以在 Linux 上为你的 Node.js 应用配置 SSL。使用 Certbot 可以简化证书的申请和续期过程,确保你的应用始终使用安全的 HTTPS 连接。

0
看了该问题的人还看了