Node express 项目绑定域名后 获取不到客户ip公网了
发布于 23 天前 作者 zanjs 134 次浏览 来自 问答

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 如何更好的绑定域名呢?

2015-12-16_131823.png

3 回复

你设置了 proxy_pass,让 nginx 把对域名的访问转发到你设的 IP 上,nginx 照做了,你还想要什么其他结果?

用户访问域名时 DNS 已经解析到你的服务器公网 IP 上了,你又用 nginx 给转发出去了。如果你不需要转发,把 location / {} 里的内容删掉,并设置 root 访问目录

server {
    listen       80;
    server_name  nnn.com;
    root /data/html/www; // 程序根目录
}

req.headers[‘x-forwarded-for’] 相应的 nginx 也需要配置

location / {
                proxy_pass   http://localhost: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 $http_host;
                proxy_set_header X-NginX-Proxy true;
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
				}

@Neil-UWA 完美解决 感谢大神

回到顶部