Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save benjaminblack/162b4fcb1d4eebb236eabe1bb5ce96bc to your computer and use it in GitHub Desktop.

Select an option

Save benjaminblack/162b4fcb1d4eebb236eabe1bb5ce96bc to your computer and use it in GitHub Desktop.
Nginx location block regular expression to proxy S3 static websites

Nginx server configuration location block which will match //host/s3/{bucket}/{path/to/resource} and transform it into a reverse proxy for an S3 bucket configured with static website hosting and named with a conventional prefix (adjust region accordingly), like //{s3prefix}-{bucket}.s3-website-us-east-1.amazonaws.com/{path/to/resource}.

E.g. assuming I prefix all of my S3 buckets with bb, like s3://bb-mybucket, and create my buckets in the us-east-1 region, then:

http://example.com/s3/mybucket/img/header.jpg

will be transformed into a proxied request to

http://bb-mybucket.s3-website-us-east-1.amazonaws.com/img/header.jpg

location ~ /s3/([^/]*)/(.*)$ {
    set $s3_bucket bb-$1;
    set $s3_resource $2;
    set $s3_host $s3_bucket.s3-website-us-east-1.amazonaws.com;
    set $s3url http://$s3_host/$s3_resource;

    resolver 8.8.8.8;
    proxy_cache off;
    proxy_intercept_errors on;
    proxy_redirect off;
    proxy_set_header Host $s3_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_hide_header x-amz-id-2;
    proxy_hide_header x-amz-request-id;
    proxy_pass $s3url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment