开发者

ASP.NET Site Redirection help

I am following the code over here https://web.archive.org/web/20211020203216/https://www.4guysfromrolla.com/articles/072810-1.aspx

to redirect http://somesite.com to http://www.somesite.com

protected void Application_BeginRequest(object sender, EventArgs e)
{
   if (Request.Url.Authority.StartsWith("www"))
      return;

   var url = string.Format("{0}://www.{1}{2}",
               Request.Url.Scheme,
               Request.Url.Authority,
               Request.Url.PathAndQuery);

   Response.RedirectPermanent(url, true);
}

How can I use this code to handle situations where http://abc.somesite.com should redirect开发者_开发问答 to www.somesite.com


I'd suggest the best way to handle this would be in the dns record, if you have control of it.


  1. If you don't know what the values will be ahead of time, you can use substring with indexof for the Url path to parse out the value you want and replace it.

  2. If you do know what it is ahead of time, you can always just do Request.Url.PathAndQuery.Replace("abc", "www");

You can also do a dns check as @aceinthehole suggested after you have parsed what you need to make sure you haven't made any mistakes.

assuming you have a string like http://abc.site.com and you want to turn abc into www then you could do something like.

string pieceToReplace = Request.Url.PathAndQuery.substring(0, Request.Url.PathAndQuery.IndexOf(".") + 1);

//here I use the scheme and entire url to make sure we don't accidentally replace an "abc" that belongs later in the url like in a word "GHEabc.com" or something.
string newUrl = Request.Url.ToString().Replace(Request.Url.Scheme + "://" + pieceToReplace, Request.Url.Scheme + "://www");

Response.Redirect(newUrl);

p.s. I don't remember if the Request.Url.Scheme already has the "://" in it or not so you will need to edit accordingly.


I don't think you can do it without access to the DNS. It sounds like you need a wildcard DNS entry:

http://en.wikipedia.org/wiki/Wildcard_DNS_record

Along with IIS configured without host headers (IP only). Then you can use code similar to the above to do what you want.

if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
  Response.Redirect('www.somesite.com');

Perhaps tighten it up some to prevent wwww.somesite.com from getting through. Anything that starts with www including wwwmonkeys.somesite.com would get through the above check. It is just an example.

asp.net mvc: How to redirect a non www to www and vice versa

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜