將真實 IP 從 Nginx 代理程式轉送到 PM2 Web 伺服器

將真實 IP 從 Nginx 代理程式轉送到 PM2 Web 伺服器

我有一個由平均堆疊提供支援並使用 PM2 提供服務的 API。它公開了一個 HTTP 端點http://89.89.89.89:8080(範例 IP)- 我可以使用瀏覽器直接存取它。

我已經安裝了 Nginx,並使用以下配置將請求重定向到同一伺服器上的 API。

server {
        listen 8081;
        server_name example.com;

        location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header  X-Forwarded-Host $remote_addr;
        proxy_pass http://127.0.0.1:8080;
        }
}

以上工作正常,我可以存取 APIhttp://89.89.89.89:8081(Nginx 連接埠),但是對目標的請求來自 127.0.0.1。我想將真實用戶的IP位址轉送給PM2。我已經搜索並嘗試了幾種解決方案,但無法使其發揮作用。

任何正確方向的幫助或指示都值得讚賞。

答案1

你需要有一個帶有模組的 nginx --with-http_realip_module,否則你應該能夠在沒有它的情況下完成它。

檢查模組是否存在執行nginx -v

如果沒有該模組,您應該在配置日誌格式中指定以下內容。例子:

log_format  main  '$http_x_forwarded_for - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent"';

access_log  /var/log/nginx/access.log  main;

real_ip_header X-Forwarded-For;

重啟 nginx 後,檢查日誌。

如果安裝了該模組,您需要相應地修改您的配置

# Directives for setting real_ip/XFF IP address in log files
set_real_ip_from    192.168.101.10; #IP address of master LB
real_ip_header      X-Forwarded-For;

real ip 模組用於將客戶端來源 IP 位址變更為標頭中的值。我們想要為來自 IP 位址為 192.168.101.10 的伺服器的流量設定真實 IP 位址。

同樣,更改後必須重新啟動 nginx 服務。

相關內容