views:

392

answers:

1

This is the code I use to redirect from www. to non www. version of my site

void Application_BeginRequest(object sender, EventArgs e)
{
    string authority = Request.Url.Authority;
    if (authority.StartsWith("www."))
    {
        authority = authority.Remove(0, 4);
        string newUrl = "http://" + authority + Request.Url.PathAndQuery;

        Response.Clear();
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", newUrl);
        Response.End();            
    }
}

this is the tool I used to validate if the code above work as expected:

http://www.internetofficer.com/seo-tool/redirect-check/

While everything works as expected for almost all users, some of them has complained they can't access the site. I logged in to their computer using TeamViewer and indeed, there was a problem. When they try to acces the site, FF and IE gives an error: it looks like the site you wanted isn't there.

What should be the problem ?

A: 

You're using .PathAndQuery, so take a look into this answer: Hyperlinks stop working in firefox after redirect?

problem solved by removing question-mark from redirect url.

So, try to use Request.Url.LocalPath property.

Rubens Farias
I want to redirect users to the same page, but wihtout www. in the URL. From "http:// www.example.com/Home.aspx?id=2" to "http:// example.com/Home.aspx?id=2"
pixel3cs
hmm, I ran out of bullets =/
Rubens Farias
Can you remove the trailing question mark if it ends the url?Something like:if(newUrl.EndsWith("?")) newUrl = newUrl.Substring(0, newUrl.Length - 2);That should only remove empty query strings, while leaving ?id=2.
mrdrbob