溫馨提示×

Node.js在CentOS中如何配置SSL證書

小樊
45
2025-07-30 18:42:16
欄目: 云計算

在CentOS系統中配置Node.js應用程序的SSL證書,可以按照以下步驟進行:

1. 獲取SSL證書

首先,你需要獲取一個SSL證書。你可以從Let’s Encrypt免費獲取,或者從其他證書頒發機構購買。

使用Let’s Encrypt獲取證書

你可以使用Certbot工具來獲取和自動續訂Let’s Encrypt證書。

sudo yum install epel-release
sudo yum install certbot python2-certbot-nginx

然后運行Certbot來獲取證書:

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

按照提示完成證書的獲取和配置。

2. 配置Nginx作為反向代理

如果你使用Nginx作為反向代理,可以在Nginx配置文件中設置SSL。

編輯Nginx配置文件(通常位于/etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf):

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應用運行在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;
    }
}

3. 配置Node.js應用程序

在你的Node.js應用程序中,你可以使用https模塊來創建一個HTTPS服務器。

首先,安裝必要的模塊:

npm install https fs

然后,創建一個HTTPS服務器:

const https = require('https');
const fs = require('fs');

const options = {
    key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem'),
    cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
};

https.createServer(options, (req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
}).listen(443);

4. 重啟Nginx和Node.js應用程序

最后,重啟Nginx和你的Node.js應用程序以應用更改。

sudo systemctl restart nginx
pm2 restart your-node-app # 如果你使用pm2管理Node.js應用

5. 驗證配置

打開瀏覽器并訪問https://yourdomain.com,你應該能夠看到你的Node.js應用程序,并且瀏覽器地址欄會顯示安全鎖圖標。

通過以上步驟,你可以在CentOS系統中成功配置Node.js應用程序的SSL證書。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女