ubuntu

Node.js在Ubuntu上如何配置SSL证书

小樊
38
2025-11-11 02:43:52
栏目: 云计算

在Ubuntu上为Node.js应用程序配置SSL证书,通常需要以下几个步骤:

  1. 获取SSL证书

    • 你可以从Let’s Encrypt免费获取SSL证书。
    • 使用Certbot工具来获取和续订证书。
  2. 安装Certbot

    • 打开终端并运行以下命令来安装Certbot:
      sudo apt update
      sudo apt install certbot python3-certbot-nginx
      
  3. 配置Nginx

    • Certbot通常与Nginx一起使用,因为它可以自动配置Nginx以使用SSL证书。
    • 编辑Nginx配置文件,通常位于/etc/nginx/sites-available/default
      sudo nano /etc/nginx/sites-available/default
      
    • 添加或修改以下内容:
      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;
      
          location / {
              proxy_pass http://localhost:3000; # 假设你的Node.js应用运行在3000端口
              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;
          }
      }
      
    • 保存并退出编辑器。
  4. 获取并安装证书

    • 运行Certbot命令来获取证书:
      sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
      
    • Certbot会自动配置Nginx并获取证书。
  5. 测试配置

    • 重新加载Nginx配置以确保一切正常:
      sudo nginx -t
      
    • 如果没有错误,重新加载Nginx:
      sudo systemctl reload nginx
      
  6. 自动续订证书

    • Certbot会设置一个cron作业来自动续订证书,通常每天检查一次。
    • 你可以手动测试续订过程:
      sudo certbot renew --dry-run
      

通过以上步骤,你就可以在Ubuntu上为Node.js应用程序配置SSL证书了。记得将yourdomain.com替换为你的实际域名,并确保Nginx配置文件中的代理设置正确指向你的Node.js应用。

0
看了该问题的人还看了