NGINX 配置 proxy_set_header Host $host 阻止设置 IP 地址

NGINX 配置 proxy_set_header Host $host 阻止设置 IP 地址

我的 NGINX 服务器有以下服务器块

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

问题是我想要获取在 nginx 上收到的确切主机名。在本例中,请求 URI /test_url 的下一跳是 example.com。我能够使用 proxy_set_header Host $host 实现这一点,但我看不到 x-real-ip 或 x-remote-ip 标头被设置。如果我删除 proxy_set_header Host $host 设置,IP 标头将被设置。有人知道为什么会出现这种情况吗?或者我应该怎么做才能同时实现这两种情况?

答案1

nginx 配置文件的大多数指令都会覆盖先前定义的指令。

这意味着您的配置proxy_set_header(在 上server)不会被考虑在您的 内部location。您必须重新应用这些规则,例如:

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

相关内容