溫馨提示×

CentOS Node.js 怎樣配置 Nginx 反向代理

小樊
42
2025-04-30 19:12:17
欄目: 編程語言

在 CentOS 上配置 Nginx 作為 Node.js 應用的反向代理,可以按照以下步驟進行:

1. 安裝 Nginx

首先,確保你的 CentOS 系統上已經安裝了 Nginx。如果沒有安裝,可以使用以下命令進行安裝:

sudo yum install epel-release
sudo yum install nginx

2. 啟動 Nginx

安裝完成后,啟動 Nginx 并設置開機自啟動:

sudo systemctl start nginx
sudo systemctl enable nginx

3. 配置 Nginx 反向代理

編輯 Nginx 的配置文件,通常位于 /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf。你可以創建一個新的配置文件或編輯現有的配置文件。

假設你的 Node.js 應用運行在 localhost3000 端口上,你可以添加以下配置:

server {
    listen 80;
    server_name your_domain.com;  # 替換為你的域名或公網 IP

    location / {
        proxy_pass http://localhost: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. 檢查配置文件

在保存配置文件后,使用以下命令檢查 Nginx 配置文件是否有語法錯誤:

sudo nginx -t

如果配置文件沒有問題,你會看到類似以下的輸出:

nginx: configuration file /etc/nginx/nginx.conf test is successful

5. 重新加載 Nginx

如果配置文件檢查通過,重新加載 Nginx 以應用新的配置:

sudo systemctl reload nginx

6. 測試反向代理

現在,你可以通過瀏覽器訪問你的域名或公網 IP,應該能夠看到你的 Node.js 應用的響應。

7. 可選配置

你可以根據需要添加更多的配置選項,例如:

  • SSL/TLS 配置:如果你需要使用 HTTPS,可以在 Nginx 中配置 SSL/TLS。
  • 緩存:可以配置 Nginx 緩存靜態資源以提高性能。
  • 安全頭:添加安全頭以提高應用的安全性。

以下是一個簡單的 SSL/TLS 配置示例:

server {
    listen 443 ssl;
    server_name your_domain.com;  # 替換為你的域名或公網 IP

    ssl_certificate /path/to/your/certificate.crt;
    ssl_certificate_key /path/to/your/private.key;

    location / {
        proxy_pass http://localhost: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;
    }
}

確保將 /path/to/your/certificate.crt/path/to/your/private.key 替換為你的 SSL 證書和私鑰的實際路徑。

通過以上步驟,你應該能夠在 CentOS 上成功配置 Nginx 作為 Node.js 應用的反向代理。

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