워드프레스는 기본적으로 모든 이미지가 'wp-content/uploads' 경로로 저장이 됩니다.

그래서 ELB로 여러대의 서버를 분산시키거나, 서버 교체시 이미지가 404나는 경우가 발생하곤 합니다.

이런 상황을 방지하고자 워드프레스와 AWS S3와 연동하는 법을 찾아보겠습니다.

※ 사전에 꼭 필요한 것들

- composer

https://aljshal.tistory.com/54

 

- php-xml

$ sudo yum install -y php-xml

 

- S3 Key

https://aljshal.tistory.com/55

 

1. AWS SDK for PHP 설치

- 아래 코드 실행 후, /var/www/html 위치에 vendor 폴더 및 관련 파일이 설치되었는지 확인

$ cd /var/www/html
$ composer require aws/aws-sdk-php

 

2. 샘플 코드 테스트

- 아래 코드를 test.php 로 저장하여 웹에서 실행

- s3 버킷에 이미지가 저장되고, 그 주소가 출력되면 성공

<?php

ini_set( 'display_errors', 1 );

require_once 'vendor/autoload.php';


use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;

echo '<pre>';

define( 'S3_KEY', 'S3_KEY');
define( 'S3_SECRET', 'S3_SECRET');
define( 'S3_BUCKET', 'S3_BUCKET');
define( 'S3_REGION', 'ap-northeast-2');

$s3 = new S3Client([
    'version' => 'latest',
    'region' => S3_REGION,
    'credentials' => [
        'key' => S3_KEY,
        'secret' => S3_SECRET,
    ]
]);

$file_url = 'https://www.example.com/sample-logo.jpg';
$s3_path = 'uploads/sample-logo.jpg';
$file_data = file_get_contents( $file_url );

try{
    $result = $s3->putObject([
        'Bucket' => S3_BUCKET,
        'Key' => $s3_path,
        'Body' => $file_data,
        'ACL' => 'public-read'
    ]);
    echo $result['ObjectURL']. PHP_EOL;
} catch ( S3Exception $e ) {
    echo $e->getMessage();
}

+ Recent posts