[英]Getting IP Address and Location of my own server instead of visiting User's
我在服務器上部署了一個 MEAN Stack 應用程序,並使用 Nginx 作為代理服務器來處理請求並重定向到應用程序的特定端口。
例如:用戶訪問 URL http://www.abcxyz.com/
並且 Nginx 訪問實際應用程序 URL http://www.abcxyz.com:1234/
,因為我的應用程序在端口 1234 上運行。
現在,出於分析目的,我在 node.js 中編寫了一個簡短的腳本,用於獲取訪問我網站的用戶的 IP 和位置。 我可以看到外部搜索的查詢,但我正在獲取我自己服務器的 IP 地址和位置。 這是為什么?
那是因為Nginx嗎? 如何解決此問題並獲取用戶的實際位置?
更新:我添加了一個對我有用的答案。 干杯;-)
如果您使用快遞:
設置非假信任代理值會導致三個重要變化:
req.hostname 的值來自 X-Forwarded-Host 頭中設置的值,可以由客戶端或代理設置。
X-Forwarded-Proto 可以由反向代理設置來告訴應用程序是 https 還是 http 甚至是無效名稱。 該值由 req.protocol 反映。
req.ip 和 req.ips 值填充了來自 X-Forwarded-For 的地址列表。
http://expressjs.com/es/guide/behind-proxies.html
app.enable('trust proxy');
app.all("*", (req, res, next) => {
console.log(req.ip, req.ips);
//Do whatever you want or call next()
});
如果你沒有使用 express,你可以從 header 中獲取 IP: x-forwarded-for
let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
如果您沒有獲得正確的 IP,則需要在 Nginx 中進行正確的設置:
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header
proxy_set_header X-Forwarded-For $remote_addr;
或者將遠程用戶 IP 附加到任何現有的 X-Forwarded-For 值:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
我想感謝
@Marcos Casagrande
的回答。 雖然我不得不在他回答后額外工作 3 小時,但會接受他的線索作為我問題的答案。
這是對我/etc/nginx/conf.d/abcxyz.com.conf
的 Nginx Conf,放在路徑/etc/nginx/conf.d/abcxyz.com.conf
。
server {
listen 80;
listen [::]:80;
server_name abcxyz.com;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location / {
proxy_pass "http://localhost:1234/";
}
}
不需要其他 Nginx Conf,在我之前的實現中,我在/etc/nginx/sites-available/default
目錄中有另一個 conf 文件,該文件與重復服務器名稱沖突。 最后,我想在重置更改之前添加使用 Nginx 測試命令。 這是一個巨大的幫助。 命令: nginx -t
。
而在 Node.js 中,這是訪問客戶端 IP 地址的最合適方式。
var getClientAddress = (req.headers['x-forwarded-for'] || '').split(',')[0]
|| req.connection.remoteAddress;
console.log(getClientAddress);
干杯;-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.