从NodeJS请求获取主机

时间:2014-09-21 07:40:16

标签: javascript node.js http

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

 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;
   }
}

1 个答案:

答案 0 :(得分:3)

问题是nginx中的proxy_pass会将主机头重写为重写时引用的任何主机。如果要覆盖该行为,可以使用proxy_set_header手动覆盖传出代理请求的主机头;

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

可以获得更详细的解释here

相关问题