WishMeLz

生活其实很有趣

express 请求者IP

正常情况下:

console.log(req.ip); // ::ffff:123.23.12.1

使用nginx代理后:

 location / {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:2012;
            proxy_redirect default;
        }

Nginx做反向代理的时候就会把客户端的Head信息写入请求的Head中

console.log(req.headers['x-forwarded-for']);  // ::ffff:123.23.12.1
console.log(req.headers['x-real-ip']);  // ::ffff:123.23.12.1
console.log(req.ip); // ::ffff:127.0.0.1