我正在尝试使用适用于 PHP 的 AWS 开发工具包以编程方式将文件上传到在 S3 控制台中设置为静态网站的存储桶。
存储桶名为 foo.ourdomain.com 并托管在 eu-west。我正在使用以下代码来尝试测试我是否可以上传文件:
$client = \Aws\S3\S3Client::factory(array('key' => bla, 'secret' => bla));
$client->upload('foo.ourdomain.com', 'test.txt', 'hello world', 'public-read');
这与示例中的情况非常相似,但是,我收到以下异常:
PHP Fatal error: Uncaught Aws\S3\Exception\PermanentRedirectException: AWS Error Code: PermanentRedirect, Status Code: 301, AWS Request ID: -, AWS Error Type: client, AWS Error Message: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint: "foo.ourdomain.com.s3.amazonaws.com"., User-Agent: aws-sdk-php2/2.4.8 Guzzle/3.7.4 curl/7.22.0 PHP/5.3.10-1ubuntu3.8
此时我很惊讶,因为在 S3 SDK 的手册中没有提到这一点。不过好吧,我找到了一个方法setEndpoint,将代码调整为:
$client = \Aws\S3\S3Client::factory(array('key' => bla, 'secret' => bla));
$client->setEndpoint('foo.ourdomain.com.s3.amazonaws.com');
$client->upload('foo.ourdomain.com', 'test.txt', 'hello world', 'public-read');
我以为那行得通,但我得到了完全相同的错误。我仔细检查过,异常中提到的端点逐字节匹配我在第二行中设置的端点。
我也尝试过使用 foo.ourdomain.com.s3-website-eu-west-1.amazonaws.com 作为端点(这是我们的 CNAME 根据 S3 控制台说明指向的主机)。也没用。
我一定是遗漏了什么,但我到处都找不到。也许设置为“静态网站”的存储桶以 SDK 当前不支持的方式表现不同?如果是这样,我在文档和管理控制台中都找不到提及它。
最佳答案
明白了。解决方案是将客户端的初始化更改为:
$client = \Aws\S3\S3Client::factory(array(
'key' => bla,
'secret' => bla,
'region' => 'eu-west-1'
));
即我需要在选项数组中显式设置区域,而不是指定端点。我想示例代码恰好使用了默认区域。
关于php - 在 Amazon AWS PHP SDK 中为 S3 客户端设置正确的端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19767832/