ASP.NET에서 도메인 변경하여 보내기

제목이 조금 이상하지만, 내용을 보면 무엇인지 이해가 될 것이다.

일부 사이트는 도메인이 2가지가 가지고 있다. 예를 들면 some.com과 some.co.kr 이다.

이런 경우 둘 중에 하나의 도메인에 우선 순위를 주기 마련이다. 보통 .com 도메인이 될 것이다.

즉, some.co.kr 로 사이트에 접속하면 some.com 으로 도메인을 변경하여 응답한다.

이렇게 전환하는 방법은 별도의 페이지를 만들거나 Redirect 모듈을 이용하는 것이다.

ASP.NET에서 이와 같은 것을 하려면 다음과 같이 할 수 있다.

global.aspx 파일

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<script RunAt="server">
/// <summary>
/// 요청 도메인을 변경한다.
/// </summary>
protected void Application_BeginRequest(object sender, EventArgs e) {
    string fromUrl = "http://some.co.kr";
    string toUrl = "http://some.com";
    string url = HttpContext.Current.Request.Url.ToString();
    if(Regex.IsMatch(url, fromUrl, RegexOptions.IgnoreCase)) {
        HttpContext.Current.Response.Status = "301 Moved Permanently";
        HttpContext.Current.Response.AddHeader("Location",
        Regex.Replace(url, fromUrl, toUrl, RegexOptions.IgnoreCase)
    );
}
</script>

이와 같이 하면 다음과 같이 웹 서버가 응답하게 된다.

GET http://some.co.kr/some/some.aspx HTTP/1.0

HTTP/1.1 301 Moved Permanently
Connection: close
Date: Mon, 02 Feb 2009 05:33:41 GMT
Location: http://some.com/some/some.aspx
Cache-Control: private
Content-Length: 0

참고