개요
티스토리에서 워드프레스로 블로그를 이전한 후 기존 포스팅을 마이그레이션한 다음
기존 블로그에서 이전한 블로그로 동일한 포스팅이 있는 경우 redirect 한 과정을 포스팅 한 적이 있다.
그 당시에는 새로운 블로그로의 유입을 조금이나마 유도하기 위한 목적이었고 그래서 단순하게 처리하였다.
하지만 최근에 통계를 보니 존재하지 않는 포스팅으로의 redirect 가 많았다.
사용자의 입장에서는 기존 블로그에 존재하는 포스트 내용을 전혀 볼 수 없게 된다.
그래서 이전한 블로그에 동일한 포스팅이 있는 경우만 redirect 하기 위해 약간의 수정을 한 과정에 대해 설명하고자 한다.
이전 포스트
워드프레스 수정
init
훅 대신에 template_redirect
훅을 사용하고
현재 URL에 해당 포스트가 있는 경우 200으로 반환하게 수정하며, 그 외에는 404로 반환한다.
// BEGIN TISTORY CORS
add_action('template_redirect', 'handle_tistory_redirect');
function handle_tistory_redirect() {
$origin = get_http_origin();
if ($origin === 'https://kkomzi.tistory.com') {
header("Access-Control-Allow-Origin: https://kkomzi.tistory.com");
header("Access-Control-Allow-Methods: GET, HEAD");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Headers: *');
if ('HEAD' == $_SERVER['REQUEST_METHOD']) {
$url_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$post_id = basename(rtrim($url_path, '/'));
if (is_numeric($post_id) && get_post($post_id)) {
status_header(200);
}
else {
status_header(404);
}
exit();
}
}
}
// END TISTORY CORS
티스토리 수정
자바스크립트 function 을 수정해서 status 코드에 따라 분기 처리한다.
<script type="text/javascript">
function redirect() {
var url = new URL(window.location.href);
if(url.pathname.substring(0) != '/') {
var newUrl = "https://blog.kkomzi.net" + url.pathname.substring(0);
fetch(newUrl, {
method: 'HEAD'
})
.then((response) => {
if(response.status === 200) {
window.location.href = newUrl;
} else {
console.log("대상 URL이 존재하지 않습니다: " + newUrl);
}
})
.catch((error) => console.log(error));
}
}
</script>
0 Comments