其他语言也是一样的,都是配置Nginx之后,在http头里面获取“x-forwarded-for”.
第一、配置Nginx
location / {
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;
proxy_pass http://127.0.0.1:8360/;
}
第二、nodejs获取真实ip
//获取ip(内网或外网)
var getIp = function(_http) {
var ipStr = _http.headers['X-Real-IP'] || _http.headers['x-forwarded-for'];
if (ipStr) {
var ipArray = ipStr.split(",");
if (ipArray || ipArray.length > 0) { //如果获取到的为ip数组
return ipArray[0];
}
} else { //获取不到时
return _http.ip().substring(_http.ip().lastIndexOf(":") + 1);
}
};
//获取外网ip
var getNetIp = function(_http) {
var ipStr = _http.headers['X-Real-IP'] || _http.headers['x-forwarded-for'];
if (ipStr) {
var ipArray = ipStr.split(",");
if (ipArray.length > 1) { //如果获取到的为ip数组
for (var i = 0; i < ipArray.length; i++) {
var ipNumArray = ipArray[i].split(".");
var tmp = ipNumArray[0] + "." + ipNumArray[1];
if (tmp == "192.168" || (ipNumArray[0] == "172" && ipNumArray[1] >= 16 && ipNumArray[1] <= 32) || tmp == "10.7") {
continue;
}
return ipArray[i];
}
}
return ipArray[0];
} else { //获取不到时
return _http.ip().substring(_http.ip().lastIndexOf(":") + 1);
}
};