How can I reduce my data transfer cost? Amazon S3 --> Cloudflare --> Visitor

后端 未结 2 1428
迷失自我
迷失自我 2021-02-13 21:04

I recently started using Amazon S3 to serve images to my visitors since this will reduce the server load. Now, there is a new problem: Today I looked into my AWS billings. I not

2条回答
  •  庸人自扰
    2021-02-13 21:54

    If you are getting "x-amz-meta-cachecontrol", it is likely you are not setting the headers correctly. It might just be the exact way you are doing it in your code. This is supposed to work. I am deducing this is php using Amazon S3 PHP Class?

    Try this:

    $s3->putObject(file_get_contents($path), $bucket, $url, S3::ACL_PUBLIC_READ, array(), array('Cache-Control' => 'max-age=31536000, public'));
    

    In the S3 PHP docs putObjectFile is listed under Legacy Methods:

    putObjectFile (string $file, 
                   string $bucket, 
                   string $uri, 
                   [constant $acl = S3::ACL_PRIVATE], 
                   [array $metaHeaders = array()], 
                   [string $contentType = null])
    

    Compare to this:

    putObject (mixed $input, 
               string $bucket, 
               string $uri, 
               [constant $acl = S3::ACL_PRIVATE], 
               [array $metaHeaders = array()], 
               [array $requestHeaders = array()])
    

    You need to set cache-control as a request header, but appears that there is no way to set request headers with putObjectFile, only meta headers. You have to use putObject and give it an empty array for meta headers and then another array with the request headers (including cache-control).

    You can also try some of the other working examples I have listed below.

    See also:

    How to set the Expires and Cache-Control headers for all objects in an AWS S3 bucket with a PHP script (php)

    Updating caching headers for Amazon S3 and CloudFront (python)

    Set cache-control for entire S3 bucket automatically (using bucket policies?)

    http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html?r=5225

提交回复
热议问题