nginx转发代理Node.js获取真实IP

发布时间:2017-11-22

先看看代理有没有加这3个头,一般情况都会有,如果有直接略过

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host  $http_host;

Node.js获取真实IP,express

var express = require('express')
var app = express()
app.get('/', (req, res) => {
    // 通过获取nginx代理头X-Real-IP 如果没有 => 尝试获取 X-Forwarded-For 还是没有,用express封装好的ip => req.ip
    var real_ip = req.get('X-Real-IP') || req.get('X-Forwarded-For') || req.ip;
    console.log(`IP:${real_ip}`);
})
Node.js
广告