var express = require('express'); var app = express(); var http = require('http'); var server = http.createServer(app); app.set('trust proxy', true);// 設置之後,req.ips是ip數組;若是未通過代理,則爲[]. 若不設置,則req.ips恆爲[] app.get('/', function(req, res){ console.log("headers = " + JSON.stringify(req.headers));// 包含了各類header,包括x-forwarded-for(若是被代理過的話) console.log("x-forwarded-for = " + req.header('x-forwarded-for'));// 各階段ip的CSV, 最左側的是原始ip console.log("ips = " + JSON.stringify(req.ips));// 至關於(req.header('x-forwarded-for') || '').split(',') console.log("remoteAddress = " + req.connection.remoteAddress);// 未發生代理時,請求的ip console.log("ip = " + req.ip);// 同req.connection.remoteAddress, 可是格式要好一些 res.send('Hello World'); }); app.listen(3000);
server { listen 4000; location / { proxy_pass http://127.0.0.1:3000; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; client_max_body_size 10m; # 容許客戶端請求的最大單文件字節數 client_body_buffer_size 128k; # 緩衝區代理緩衝用戶端請求的最大字節數, proxy_connect_timeout 90; # nginx跟後端服務器鏈接超時時間(代理鏈接超時) proxy_send_timeout 90; # 後端服務器數據回傳時間(代理髮送超時) proxy_read_timeout 90; # 鏈接成功後,後端服務器響應時間(代理接收超時) proxy_buffer_size 4k; # 設置代理服務器(nginx)保存用戶頭信息的緩衝區大小 proxy_buffers 4 32k; # proxy_buffers緩衝區,網頁平均在32k如下的設置 proxy_busy_buffers_size 64k; # 高負荷下緩衝大小(proxy_buffers*2) proxy_temp_file_write_size 64k; } }
headers = {"host":"127.0.0.1:3000","connection":"keep-alive","k2":"v2","k1":"v1","cache-control":"no-cache","user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2687.0 Safari/537.36","postman-token":"f48d86ee-5375-6768-6f0f-7af1b51f8676","accept":"*/*","accept-encoding":"gzip, deflate, sdch","accept-language":"zh-CN,zh;q=0.8,en;q=0.6"} x-forwarded-for = undefined ips = [] remoteAddress = ::ffff:127.0.0.1 ip = ::ffff:127.0.0.1
headers = {"x-real-ip":"127.0.0.1","x-forwarded-for":"127.0.0.1","host":"127.0.0.1","connection":"close","k2":"v2","k1":"v1","cache-control":"no-cache","user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2687.0 Safari/537.36","postman-token":"17c79ae7-f00f-6d5f-279a-99d295cbf7d5","accept":"*/*","accept-encoding":"gzip, deflate, sdch","accept-language":"zh-CN,zh;q=0.8,en;q=0.6"} x-forwarded-for = 127.0.0.1 ips = ["127.0.0.1"] remoteAddress = ::ffff:127.0.0.1 ip = 127.0.0.1
// 無需設置`app.set('trust proxy', true);` function getReqRemoteIp(req){return (req.headers['x-forwarded-for'] || '').split(',')[0] || req.ip;};
或者是:node
var user_ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;