Nginx pass all requests to specific S3 file

2019-05-19 06:42发布

问题:

I have an S3 bucket with the static contents of my site and I have an EC2 instance that receives all of the traffic to the site.

I want to have every request to the EC2 return a specific file from my S3, but I want to keep the URL the same as the user inserted it.

Example: Let's assume that my file is located in /path/index.html If the user makes a request to www.mydomain.com, I want to serve that file, and if the user makes a request to www.mydomain.com/some/random/path/ I still want to serve the same file. The last requirement is that the location will stay the same. That is, the user will still see www.mydoamin.com and www.mydoamin.com/some/random/path/ in the browser, even though the same file was served.

Here's the nginx config file I have so far, which doesn't seem to work:

server {
    listen 80;
    ssl off;

    location / {
            proxy_http_version     1.1;
            proxy_set_header       Host 'some-host.s3.amazonaws.com';
            proxy_set_header       Authorization '';
            proxy_hide_header      x-amz-id-2;
            proxy_hide_header      x-amz-request-id;
            proxy_hide_header      Set-Cookie;
            proxy_ignore_headers   "Set-Cookie";
            proxy_buffering        off;
            proxy_intercept_errors on;


            resolver               8.8.4.4 8.8.8.8 valid=300s;
            resolver_timeout       10s;

            proxy_pass             http://some-host.s3.amazonaws.com/front-end/index.html;
    }
}

Any thoughts on how to make this work?

Thanks!

回答1:

I ended up using a variable. This solved the problem:

server {
    listen 80;
    ssl off;

    location / {
            proxy_http_version     1.1;
            proxy_set_header       Host 'some-host.s3.amazonaws.com';
            proxy_set_header       Authorization '';
            proxy_hide_header      x-amz-id-2;
            proxy_hide_header      x-amz-request-id;
            proxy_hide_header      Set-Cookie;
            proxy_ignore_headers   "Set-Cookie";
            proxy_buffering        off;
            proxy_intercept_errors on;

            resolver               172.16.0.23 valid=300s;
            set $indexfile         "some-host.s3.amazonaws.com/front-end/index.html";
            proxy_pass             http://$indexfile;
    }
}