Node.js代码
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.set('trust proxy', true);
app.get('/', function(req, res){
console.log("headers = " + JSON.stringify(req.headers));
console.log("x-forwarded-for = " + req.header('x-forwarded-for'));
console.log("ips = " + JSON.stringify(req.ips));
console.log("remoteAddress = " + req.connection.remoteAddress);
console.log("ip = " + req.ip);
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;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
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
提取出来的一个工具函数
function getReqRemoteIp(req){return (req.headers['x-forwarded-for'] || '').split(',')[0] || req.ip;};
参考
- How to determine a user’s IP address in node
- Express.js: how to get remote client address