Ubuntu

過濾以僅通過 Nginx 反向代理傳遞特定標頭

  • September 8, 2020

例如這裡是前端項目設置的標題列表,預設發送所有

* accept: application/json
* accept-encoding: gzip, deflate, br
* accept-language: en-GB,en-US;q=0.9,en;
* authorization: xxxx
* cache-control: no-cache
* content-type: application/json
* pragma: no-cache
* referer: xxx
* sec-fetch-dest: empty
* sec-fetch-mode: cors
* sec-fetch-site: same-origin
* x-request-id: xxx-xxx-xxx

我有一個 Nginx 位置塊(AWS Cloudfront),對於這個特定的 API 端點,我只想將特定的標頭(僅傳遞“授權”和“x-request-id”)傳遞給上游,我如何配置 proxy_set_header 指令?

location /some/special/api/ {
   resolver 10.0.0.2 valid=60s;
   proxy_pass         https://some.special.com/api/;
   proxy_redirect     off;

   proxy_set_header   Host             $host;
   proxy_set_header   X-Real-IP        $remote_addr;
   proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
   proxy_max_temp_file_size 0;
   client_max_body_size       50m;
   client_body_buffer_size    128k;
   proxy_connect_timeout      600;
   proxy_send_timeout         600;
   proxy_read_timeout         600;
   proxy_buffer_size          4k;
   proxy_buffers              4 32k;
   proxy_busy_buffers_size    64k;
   proxy_temp_file_write_size 64k;
}

您可以設置proxy_pass_request_headers off;禁用向上游發送所有請求標頭,然後將proxy_set_header <header>;其用於您明確要傳遞的每個標頭。

例如,您可以添加:

proxy_pass_request_headers off;
proxy_set_header Authorization $http_authorization;
proxy_set_header X-Request-ID $http_x_request_id;

引用自:https://serverfault.com/questions/1033131