2014-09-21 56 views
2

我有一个基本的http服务器运行在多个域指向的服务器上。我需要找到请求的主机(请求来自的域)。从NodeJS请求获取主机

require("http").createServer(function (req, res) { 
    console.log(req.headers.host);     
    res.end("Hello World!");      
}).listen(9000);         

req.headers.host的值是127.0.0.1:9000代替域名(example.com左右)。

如何从请求对象获取域名?

节点服务器通过nginx代理。配置是这样的:

server { 
    listen 80; 
    server_name ~.*; 
    location/{ 
     proxy_pass http://127.0.0.1:9000; 
    } 
} 
+0

节点服务器如何代理? nginx的? – 2014-09-21 07:45:26

+0

@JoachimIsaksson没错。 – 2014-09-21 07:46:44

+1

@JoachimIsaksson不要忘了添加一个答案。问题解决了。 :-) – 2014-09-21 07:49:40

回答

3

的问题是,在proxy_pass nginx的重写主机头到任何主机在你重写引用。如果您想覆盖该行为,可以使用proxy_set_header手动覆盖传出 - 代理 - 请求的主机头;

server { 
    listen 80; 
    server_name ~.*; 
    location/{ 
     proxy_pass http://127.0.0.1:9000; 
     proxy_set_header Host $http_host; 
    } 
} 

有些更详细的解释可用here