在 CentOS 上配置 Nginx 作為 Node.js 應用的反向代理,可以按照以下步驟進行:
首先,確保你的 CentOS 系統上已經安裝了 Nginx。如果沒有安裝,可以使用以下命令進行安裝:
sudo yum install epel-release
sudo yum install nginx
安裝完成后,啟動 Nginx 并設置開機自啟動:
sudo systemctl start nginx
sudo systemctl enable nginx
編輯 Nginx 的配置文件,通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/conf.d/default.conf
。你可以創建一個新的配置文件或編輯現有的配置文件。
假設你的 Node.js 應用運行在 localhost
的 3000
端口上,你可以添加以下配置:
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;
}
}
在保存配置文件后,使用以下命令檢查 Nginx 配置文件是否有語法錯誤:
sudo nginx -t
如果配置文件沒有問題,你會看到類似以下的輸出:
nginx: configuration file /etc/nginx/nginx.conf test is successful
如果配置文件檢查通過,重新加載 Nginx 以應用新的配置:
sudo systemctl reload nginx
現在,你可以通過瀏覽器訪問你的域名或公網 IP,應該能夠看到你的 Node.js 應用的響應。
你可以根據需要添加更多的配置選項,例如:
以下是一個簡單的 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 應用的反向代理。