Skip to content

Instantly share code, notes, and snippets.

@josue
Last active March 7, 2023 07:31
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save josue/11233860 to your computer and use it in GitHub Desktop.
Save josue/11233860 to your computer and use it in GitHub Desktop.
Simple Nginx Proxy to S3 Bucket Asset
server {
listen 80;
listen 443 default_server ssl;
ssl on;
ssl_certificate /etc/ssl/certs/myssl.crt;
ssl_certificate_key /etc/ssl/private/myssl.key;
server_name *.example.com;
root /var/www/vhosts/website;
location / {
index index.php index.html index.htm;
if (-f $request_filename) {
break;
}
if (-d $request_filename) {
break;
}
# using PHP app routing
rewrite ^(.+)$ /index.php?url=$1 last;
}
# Proxy any URL request to S3 bucket and remove any Amazon headers
location ~ "^/asset/(.*)$" {
add_header X-Asset-Location $hostname;
set $bucket "<BUCKET-NAME>";
set $key $1;
rewrite .* /$key break;
# no client headers
proxy_pass_request_headers off;
# let amazon take the buffering load
proxy_buffering off;
# let amazon retry a few times if first timeouts are 5xx response
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_set_header Host $bucket.s3.amazonaws.com;
proxy_pass http://s3.amazonaws.com;
proxy_hide_header "x-amz-id-2";
proxy_hide_header "x-amz-request-id";
}
}
@BigglesZX
Copy link

Thanks for this. I found I had to omit the Host header you use and proxy_pass straight to the bucket URL, otherwise Amazon would issue a 307 redirect which nginx would pass on, turning the proxy into a redirect! I also had to specify a resolver after making that change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment