Ionică Bizău
Ionică Bizău

Reputation: 113335

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

Upvotes: 2

Views: 777

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

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.

Upvotes: 3

Related Questions