0

My NGINX server has following Server Block

upstream main {
  least_conn;
  #Add entries one per upstream server
  server web01:4000 max_fails=3 fail_timeout=5s;
  server web01:4001 max_fails=3 fail_timeout=5s;
}
server {  
  ssl_prefer_server_ciphers on;
  ssl_protocols TLSv1.2;
  ssl_ciphers EECDH+ECDSA+AESGCM;
  ssl_certificate  webserver.pem;
  ssl_certificate_key webserver.key;
  server_tokens off;
  listen              443 ssl;
  allow all;
  server_name         example.com;
  proxy_set_header x-real-ip $proxy_add_x_forwarded_for;
  proxy_set_header x-remote-ip $remote_addr;
  proxy_hide_header Server;
  proxy_hide_header x-powered-by;

  location /test_url {
    proxy_pass http://main;
    proxy_set_header Host $host;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
  }

  location    / {
    proxy_pass http://main;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
  }
}

The question is I want to get the exact hostname which was received at nginx. In this case example.com at the next hop for request URI /test_url. I am able to achieve that with proxy_set_header Host $host but then I do not see x-real-ip or x-remote-ip headers being set anymore. If I remove proxy_set_header Host $host settings, the IP headers are getting set. Does anyone have any idea, why this behaviour or what I should do to achieve both?

strange
  • 3
  • 2

1 Answers1

0

Most directives of nginx' config file do overwrite the previously defined.

That means your config proxy_set_header (on server) IS NOT TAKEN into account INSIDE your location. You have to re-apply those rules like:

server {  
  ssl_prefer_server_ciphers on;
  ssl_protocols TLSv1.2;
  ssl_ciphers EECDH+ECDSA+AESGCM;
  ssl_certificate  webserver.pem;
  ssl_certificate_key webserver.key;
  server_tokens off;
  listen              443 ssl;
  allow all;
  server_name         example.com;
  proxy_set_header x-real-ip $proxy_add_x_forwarded_for;
  proxy_set_header x-remote-ip $remote_addr;
  proxy_hide_header Server;
  proxy_hide_header x-powered-by;

  location /test_url {
    proxy_pass http://main;
    proxy_set_header Host $host;
    proxy_set_header x-real-ip $proxy_add_x_forwarded_for;
    proxy_set_header x-remote-ip $remote_addr;    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
  }

  location    / {
    proxy_pass http://main;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
  }
}
boppy
  • 521
  • 2
  • 6
  • Thanks @boppy, that clarifies. Strange they don't have this behaviour documented anywhere or may be I couldn't find any. – strange Apr 13 '23 at 04:51
  • They do point it out in the docs under ["inheritance"](https://docs.nginx.com/nginx/admin-guide/basic-functionality/managing-configuration-files/#inheritance). But I agree it's not as clear as it could be... ;) – boppy Apr 13 '23 at 07:34