Nginx Reverse Proxy – How to Filter Specific Headers

amazon-cloudfrontnginxUbuntu

For example here is a list of headers set by the frontend project and send all by default

* 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

I have an Nginx location block (AWS Cloudfront) that for this specific API endpoint, I want to only pass specific headers (only passing 'authorization' and 'x-request-id') to the upstream, how I can configure the proxy_set_header directive?

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

Best Answer

You may set proxy_pass_request_headers off; to disable sending all request headers upstream, and then use proxy_set_header <header>; for each header that you explicitly want to pass.

For example, you could add:

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