Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the more recommended way to 301 redirect in asp.net?

I've googled everything, and I've read a ton of different responses -- some I've tried to implicate with no success. I'm not a professional programmer, but I thank people in this forum for teaching me so much about everything, from jquery to doctypes, to you name it!

I have a website developed in VWD 2010 Express. I just want to know 2 things:

  1. I know it's bad for search engines/duplicate content to have yourdomain and www.yourdomain both, so I want to set up a 301 redirect so that if an end-user types in mydomain, they're automatically redirected to www.mydomain (with the www).

  2. I've moved some pages that aren't in the root, but in folders. So I want to replace the outdated page with the new location. I want to do this by automatically redirecting them from www.mydomain/services/engineering.aspx to www.mydomain/products/engineering.aspx.

Is this difficult? Is it (recommended) to use .htaccess, or web.config, or something else?

Thank you for your time in reading this, and I sincerely appreciate any and all feedback.

Jason Weber

like image 459
Jason Weber Avatar asked Jan 07 '12 19:01

Jason Weber


1 Answers

Unless I've misunderstood .htacess is for Apache and if you are coding in ASP.Net you are almost certainly using IIS. So igonore the .htaccess stuff in your research.

You could use some kind of URL Rewriter for your redirects but that can get very complex. If i were you I would keep it as simple as possible and do your old page 301 redirects in the Page_Load event i.e.

protected void Page_Load(object sender, System.EventArgs e)
{
   Response.Status = "301 Moved Permanently";
   Response.AddHeader("Location","http://www.domainname.com/new-page.aspx");
}

For your canonical redirect (non www to www) you could do similar in the Global.asax file in Application_BeginRequest to detect the non www variant i.e.

if (HttpContext.Current.Request.Url.ToString().ToLower().Contains( 
    "http://mysite.com")) 
{ 
    HttpContext.Current.Response.Status = "301 Moved Permanently"; 
    HttpContext.Current.Response.AddHeader("Location", 
        Request.Url.ToString().ToLower().Replace( 
            "http://mysite.com", 
            "http://www.mysite.com")); 
} 

(this isn't my code it came from here)

This is what I would do anyway - it has the benefit of being easy to understand and keep you out of the way of any strange web server config which I find a bit of a black box sometimes.

like image 102
Crab Bucket Avatar answered Sep 23 '22 18:09

Crab Bucket