블로그를 이전한 경우 기존 포스트가 있는 경우만 redirect 하기

Apr 2, 2025 | 0 comments

개요

티스토리에서 워드프레스로 블로그를 이전한 후 기존 포스팅을 마이그레이션한 다음
기존 블로그에서 이전한 블로그로 동일한 포스팅이 있는 경우 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>

Learn more on this topic

Related Blog Posts

워드프레스 Github 플러그인

워드프레스 Github 플러그인

워드프레스에서 Github 저장소를 포함하기 위해 사용 중이던 Embed Block for GitHub 플러그인의 버그 발생과 더 이상 유지 보수가 안되는 상황에서 새로운 플러그인(Github Embed)을 소개하고 해당 플러그인으로 대체 하게 된 상황에 대해 설명합니다.

read more

Join in the conversation

Leave a Comment

0 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

무료 온라인 전광판

전광판

텍스트를 입력하고 텍스트 효과 및 배경효과 를 변경해서 전체화면으로 표시할 수 있는 전광판 용도로 사용하실 수 있습니다. 각종 스포츠 및 공연 관람시 응원 용도로 사용이 가능합니다.

Carousel

여러개의 슬라이드를 추가하여 프레젠테이션 및 이미지 슬라이드 용도로 사용하실 수 있습니다. 브라우저가 포함된 IT 기기로 큰 모니터에 연결하여 매장 내 공지사항 및 메뉴소개를 이미지로 표시할 수 있습니다.

Pin It on Pinterest

Shares
Share This

Share This

Share this post with your friends!

Shares