简体   繁体   中英

Get host from NodeJS request

I have a basic http server that runs on a server where multiple domains point to. I need to find the host of the request (the domain where the request is coming from).

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

req.headers.host 's value is 127.0.0.1:9000 instead of the domain name ( example.com or so).

How can I get the domain name from request object?

The node server is proxied via nginx . The configuration is like this:

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

The issue is that proxy_pass in nginx rewrites the host header to whatever host is referenced in your rewrite. If you want to override that behavior, you can manually override the host header of the outgoing - proxied - request using proxy_set_header ;

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

A somewhat more detailed explanation is available here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM