検索

ホームページ  >  に質問  >  本文

node.js - Node express 项目绑定域名后 获取不到客户ip公网了

node 代码

var express = require('express');
var app = express();
var os = require('os');
var http = require('http');
var cors = require('cors');


app.use(cors());


app.get('/', cors(),function(req, res){  
  var ip = getClientIp(req).match(/\d+\.\d+\.\d+\.\d+/); 
  console.log(ip);
});


function getClientIp(req) {
        return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
}

app.listen(8081);
console.log('listening on port http://localhost:8081/');

nginx 代理

server  {
    listen 80;
    server_name nnn.com;
    
    location / {
        proxy_set_header  X-real-IP $remote_addr;
        proxy_pass      http://127.0.0.1:8081;
    }

       access_log  /home/wwwlogs/nnn.com.log  access;
 }

直接访问服务器的ip 是正常返回客户端的ip

而访问 nginx 代理转向 的域名地址 返回的ip 却是 127.0.01

nginx 转向的 proxy_pass 地址是多少 ,返回的就是多少

node 如何更好的绑定域名呢?

天蓬老师天蓬老师2778日前593

全員に返信(3)返信します

  • 高洛峰

    高洛峰2017-04-17 13:13:08

    req.ip
    http://expressjs.com/en/4x/api.html#req.ip

    trust proxy
    http://expressjs.com/en/4x/api.html#trust.proxy.options.table

    nginx.conf

      location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      }

    返事
    0
  • 迷茫

    迷茫2017-04-17 13:13:08

    终有完成了

    修改 nginx

    server  {
        listen 80;
        server_name nnn.com;
        
        location / {
            proxy_pass      http://localhost:8081;
            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 $http_host;
            proxy_set_header X-NginX-Proxy true;
        }
    
           access_log  /home/wwwlogs/nnn.com.log  access;
     }

    返事
    0
  • 迷茫

    迷茫2017-04-17 13:13:08

    可以参考我的文章:https://segmentfault.com/a/1190000005797170,拿走不谢。

    返事
    0
  • キャンセル返事