Search code examples
nginxamazon-s3http-headersproxypass

Nginx | headers with add_header ignored when proxy_pass is used for S3 hosted file


I've a Nginx configuration, where I get certain files from AWS S3 bucket, like call from *.my.api.com/file.js will get the file from X folder in S3.

I've an exceptional domain (like xx.my.api.com) for which I will add the

  • Cache-Control "no-store, no-cache";
  • Pragma "no-cache";

headers and for the rest of *.my.api.com the headers will be default (it's cache-control: public now).

On my local environment, the file is hosted on my machine, so the headers are set correctly. However, on production, the headers come as default as cache-control: public.

I've read answers like this saying there should be no trouble with it, but it's not working for me.

Is there anything I'm doing wrong? Is it related to the file being hosted on AWS?

My Nginx configuration is as below:

server {
    listen 80;
    root /var/xyz/public;
    index index.html index.htm;
    server_name my.api.com *.my.api.com;

    add_header Access-Control-Allow-Origin "*";

    if ($http_host ~* "^(.*).my.api.com$"){
        set $myName $1;
    }

    location ~ /myfile.js {
        resolver 8.8.8.8;
        proxy_buffering off;
        proxy_set_header Content-Length "";
        proxy_set_header Cookie "";
        proxy_method GET;
        proxy_pass_request_body off;
        proxy_max_temp_file_size 0;

        if ($myName = "mySpecialName") {
            proxy_pass http://path/to/aws/s3/bucket/file.js;

            add_header Cache-Control "no-store, no-cache";
            add_header Pragma "no-cache";
            add_header X-XSS-Protection "1";
            add_header X-Frame-Options "SAMEORIGIN";
            add_header X-Content-Type-Options nosniff;
        }

        if ($query_string !~* "myQueryString=([^&]*)") {
            proxy_pass http://path/to/aws/s3/bucket/file.js;
        }

        if ($query_string ~* "myQueryString=([^&]*)") {
            proxy_pass http://path/to/some/other/aws/s3/bucket/file.js;
        }
    }
}

I've tried:

  • always
  • proxy_pass_request_headers on
  • proxy_set_header
  • copying the server code and adjusting for xx.my.api.com only
  • proxy_hide_header (can't be used because of if block)
  • more_set_headers

but none of them worked.

Any help would be appreciated, thanks in advance.


Solution

  • We've solved it by adding the headers from our DNS panel, which was used for caching the file stored in S3.