Quantcast
Channel: kkomzi
Viewing all articles
Browse latest Browse all 142

javascript redirect to another domain by response.ok with cors

$
0
0

WordPress로 이전 한지 꽤 시간이 지났음에도 아직도 예전 블로그 글들이 오래전에 작성된 거라 더 노출이 잘 되는듯 하다

그래서 이전 블로그 조회시 현재 블로그에 동일한 글이 있는 경우 Page 를 Redirect 하게 끔 수정해 보았다.

두 사이트 모두 permalink 를 동일한 형식으로 사용중이고, 이전 사이트 에서 마이그레이션(링크 참조) 한 상태라

일부러 삭제한 글을 제외하면 동일한 경로에 존재한다.

현재 WordPress 사이트에 CORS 설정이 필요하다

Origin 은 정해져 있고, GET Method 를 사용해서 접근할 예정이라 아래 코드를 테마 파일의 function.php 파일에 추가해 주었다.

// BEGIN TISTORY CORS
add_action('init', '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, OPTIONS");
        header("Access-Control-Allow-Credentials: true");
        header('Access-Control-Allow-Headers: *');
        if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
            status_header(200);
            exit();
        }
    }
}
// END TISTORY CORS

이전 사이트의 Head 태그 사이에 아래 Javascript 코드를 추가한다.

간단하게 메인 페이지가 아닌 경우 Pathname 을 사용해서 response.ok 인 경우만 redirect 하는 코드이다.

태그 및 카테고리 페이지를 위해서는 조건 추가가 필요하겠지만, 그냥 이쯤에서 만족하는 걸로…..

<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: 'GET'
		})
		.then((response) => {
			if(response.ok) {
				//window.location.replace(newUrl);
				window.location.href = newUrl;
			} else {
				console.log(response);
			}
		})
		.catch((error) => console.log(error))
		;
	}
}
</script>

그리고 Body 태그의 onload 이벤트에서 해당 function 을 호출합니다.

<body onload="redirect()">

The post javascript redirect to another domain by response.ok with cors appeared first on kkomzi.


Viewing all articles
Browse latest Browse all 142

Trending Articles