본문 바로가기

웹개발/PHP

AWS S3 사용시 중국의 Great Firewall에 의한 이미지 차단 우회하기

아마존 웹서비스(AWS)의 EC2 + S3를 이용하여 웹사이트를 서비스 하는 분들이 많습니다. S3에 이미지를 저장할 경우, 중국에서 웹사이트 접속시 해당 이미지가 표시되지 않습니다. 

GreatFirewall에 의한 차단 때문인데요. 워드프레스에서 차단을 우회하기 위한 코드를 공유합니다.


원리 : 워드프레스 필터를 사용하여 본문의 img 태그의 src를 추출하여 base64 URL로 인코딩하여 반환합니다.

Thumbnail image와 content의 내용을 찾아서 교체합니다. 


아래 내용을 적절히 수정해서 사용하시면 됩니다.


function cs_modify_post_thumbnail_url_html($html, $post_id, $post_thumbnail_id, $size, $attr) {
return apply_filters('cs_html_image_urls_to_base64', $html);
}
add_filter('post_thumbnail_html', 'cs_modify_post_thumbnail_url_html', 99, 5);

// 중국은 S3가 차단되므로 경로를 우회함
function cs_cn_modify_static_url($content) {
$from_domain = 'http://mybucketname.s3-ap-northeast-1.amazonaws.com/uploads/';
$new_domain = home_url() . '?path=' ;

$content = str_replace($from_domain, $new_domain, $content);
return $content;
}
add_filter('cs_cn_modify_static_url', 'cs_cn_modify_static_url', 99, 1);

//이미지 URL을 base64로 인코딩하는 함수
function cs_image_url_to_base64($url) {
$imgData = base64_encode(file_get_contents($url));
$src = 'data:image/png'.';base64,'.$imgData;
return $src;
}

//HTML내용에서 Image URL을 추출하여 Base64로 인코딩하는 함수
function cs_html_image_urls_to_base64($content) {
//URL검증
$from_domain = 'http://myhomepage.com/';

preg_match_all("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i", $content, $matches);
$all_urls = $matches[1];

for($i=0;$i<sizeof($all_urls); $i++) {
if(strpos($all_urls[$i], $from_domain) !== false)
$content = str_replace($all_urls[$i], er_image_url_to_base64($all_urls[$i]), $content);
}
return $content;
}
add_filter('cs_html_image_urls_to_base64', 'cs_html_image_urls_to_base64', 99, 1);

//본문 컨텐츠의 이미지 필터
add_filter('the_content', 'cs_html_image_urls_to_base64', 99, 1);