Node.js中,获取req请求的原始IP
Node.js代码
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);
Nginx配置
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; } }
运行结果(使用Postman发送GET请求)
1. 不使用代理
命令行输出:
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
2. 使用代理
命令行输出
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;};
或者是:
var user_ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;