Skip to content

Instantly share code, notes, and snippets.

@viccherubini
Created September 24, 2014 15:06
Show Gist options
  • Save viccherubini/e3107493f078516555f3 to your computer and use it in GitHub Desktop.
Save viccherubini/e3107493f078516555f3 to your computer and use it in GitHub Desktop.
AWS SDK base_url Questions
<?php
// Configuration, using AWS SDK 2.6.16
return [
'includes' => ['_aws'],
'services' => [
'default_settings' => [
'params' => [
'key' => 'xxx',
'secret' => 'yyyy',
'base_url' => 'http://files.example.com'
]
]
]
];
// Assume $s3Client is constructed with config above.
$result = $s3Client->putObject([
'Bucket' => 'files.example.com',
'Key' => 'image.jpg',
'SourceFile' => '/path/to/image.jpg',
'ContentType' => 'image/jpeg',
'ACL' => CannedAc::PUBLIC_READ
]);
// Receive this error:
// [curl] 6: Couldn't resolve host 'files.example.com.files.example.com' [url] http://files.example.com.files.example.com/image.jpg
// It seems it attempts to create the URL as: scheme://<bucket-name>.<base-url>.
// If you have a CNAME that points files.example.com to files.example.com.s3.amazonaws.com this won't work.
@jeremeamia
Copy link

Ah ha. I see what is happening.

Normally, S3 URLs look something like this: https://s3.amazonaws.com/bucket/key (we call this "path-style"). However, under most conditions, the SDK transforms this to be https://bucket.s3.amazonaws.com/key (we call this "virtual-style"). The transformation is done by Aws\S3\BucketStyleListener, and this is what is causing your doubled-up "files.example.com.files.example.com".

Using cname URLs, like you are trying to do, is not exactly supported by the SDK, but it can be done easily with an event listener.

Here is a code sample that demonstrates how to hook into the Guzzle request cycle and fix the URL before the request is sent.

<?php

$s3Client = \Aws\S3\S3Client::factory([
    // {credentials}
    'scheme' => 'http',
]);

$s3Client->getEventDispatcher()->addListener('request.before_send', function ($event) {
    $event['request']->setHost('files.example.com');
});

$result = $s3Client->putObject([
    'Bucket'     => 'files.example.com',
    'Key'        => 'image.jpg',
    'SourceFile' => '/path/to/image.jpg',
    'ACL'        => 'public-read',
]);

Note: I have tested that this transforms the URL correctly, but not that it actually works with the cname'd bucket (since I don't have anything like that setup currently). Please give this a try and let me know if it works in the way you are expecting.

@yellow1912
Copy link

@jeremeamia 1 year later and I'm finding this info useful. I setup cname with aws sdk php using this information here:

aws/aws-sdk-php#347

The getObjectUrl works fine yet the upload part gives me the exact same issue as described above. I will try your solution now. I wonder if this is caused by me using SDK 2?

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