过滤仅通过 Nginx 反向代理传递特定标头

过滤仅通过 Nginx 反向代理传递特定标头

例如,这是前端项目设置的标头列表,默认情况下会发送所有标头

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

答案1

您可以设置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;

相关内容