Nginx as reverse proxy doesn’t pass client host

nginx

I have Nginx server which works as reverse proxy for an nodejs app.

Nginx config example:

server {

  server_name www.example.com

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8796;
    proxy_redirect off;
  }
}

Currently when proxying requests $host variable or passed Host header always contains server_name value (domain of the server where nginx is started on).

This way req.headers['Host'] always has www.example.com value.

Can Nginx (used as reverse proxy in my case) pass proper request client hostname to the proxied application below (as Host header)?

Best Answer

You have missed to set the HTTP protocol version to 1.1 (default is HTTP/1.0) and your variable for the HTTP host name was wrong.

See fixed example below:

server {

  server_name www.example.com

  location / {
    proxy_http_version 1.1;
    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_pass http://127.0.0.1:8796;
    proxy_redirect off;
  }
}