Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect with "www" URL's to without "www" URL's or vice-versa?

I am using ASP.NET 2.0 C#. I want to redirect all request for my web app with "www" to without "www"

www.example.com to example.com

Or

example.com to www.example.com

Stackoverflow.com is already doing this, I know there is a premade mechanism in PHP (.htaccess) file. But how to do it in asp.net ?

Thanks

like image 326
djmzfKnm Avatar asked Feb 06 '09 19:02

djmzfKnm


4 Answers

There's a Stackoverflow blog post about this.

https://blog.stackoverflow.com/2008/06/dropping-the-www-prefix/

Quoting Jeff:

Here’s the IIS7 rule to remove the WWW prefix from all incoming URLs. Cut and paste this XML fragment into your web.config file under

<system.webServer> / <rewrite> / <rules>

<rule name="Remove WWW prefix" >
<match url="(.*)" ignoreCase="true" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\.domain\.com" />
</conditions>
<action type="Redirect" url="http://domain.com/{R:1}"
    redirectType="Permanent" />
</rule>

Or, if you prefer to use the www prefix, you can do that too:

<rule name="Add WWW prefix" >
<match url="(.*)" ignoreCase="true" />
<conditions>
<add input="{HTTP_HOST}" pattern="^domain\.com" />
</conditions>
<action type="Redirect" url="http://www.domain.com/{R:1}"
    redirectType="Permanent" />
</rule>
like image 156
shsteimer Avatar answered Nov 15 '22 16:11

shsteimer


I've gone with the following solution in the past when I've not been able to modify IIS settings.

Either in an HTTPModule (probably cleanest), or global.asax.cs in Application_BeginRequest or in some BasePage type event, such as OnInit I perform a check against the requested url, with a known string I wish to be using:

public class SeoUrls : IHttpModule
{
  #region IHttpModule Members

  public void Init(HttpApplication context)
  {
      context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
  }

  public void Dispose()
  {
  }

  #endregion

  private void OnPreRequestHandlerExecute(object sender, EventArgs e)
  {
    HttpContext ctx = ((HttpApplication) sender).Context;
    IHttpHandler handler = ctx.Handler;

    // Only worry about redirecting pages at this point
    // static files might be coming from a different domain
    if (handler is Page)
    {
      if (Ctx.Request.Url.Host != WebConfigurationManager.AppSettings["FullHost"])
      {
        UriBuilder uri = new UriBuilder(ctx.Request.Url);

        uri.Host = WebConfigurationManager.AppSettings["FullHost"];

        // Perform a permanent redirect - I've generally implemented this as an 
        // extension method so I can use Response.PermanentRedirect(uri)
        // but expanded here for obviousness:
        response.AddHeader("Location", uri);
        response.StatusCode = 301;
        response.StatusDescription = "Moved Permanently";
        response.End();
      }
    }
  }
}

Then register the class in your web.config:

<httpModules>
  [...]
  <add type="[Namespace.]SeoUrls, [AssemblyName], [Version=x.x.x.x, Culture=neutral, PublicKeyToken=933d439bb833333a]" name="SeoUrls"/>
</httpModules>

This method works quite well for us.

like image 42
Zhaph - Ben Duguid Avatar answered Nov 15 '22 14:11

Zhaph - Ben Duguid


The accepted answer works for a single URL or just a few, but my application serves hundreds of domain names (there are far too many URLs to manually enter).

Here is my IIS7 URL Rewrite Module rule (the action type here is actually a 301 redirect, not a "rewrite"). Works great:

<rule name="Add WWW prefix" >
  <match url="(.*)" ignoreCase="true" />
  <conditions>
   <add input="{HTTP_HOST}" negate="true" pattern="^www\.(.+)$" />
  </conditions>
  <action type="Redirect" url="http://www.{HTTP_HOST}/{R:1}" 
       appendQueryString="true" redirectType="Permanent" />
</rule>
like image 31
Peter J Avatar answered Nov 15 '22 16:11

Peter J


In order to answer this question, we must first recall the definition of WWW:

World Wide Web: n. Abbr. WWW

  • The complete set of documents residing on all Internet servers that use the HTTP protocol, accessible to users via a simple point-and-click system.
  • n : a collection of internet sites that offer text and graphics and sound and animation resources through the hypertext transfer protocol. By default, all popular Web browsers assume the HTTP protocol. In doing so, the software prepends the 'http://' onto the requested URL and automatically connect to the HTTP server on port 80. Why then do many servers require their websites to communicate through the www subdomain? Mail servers do not require you to send emails to [email protected]. Likewise, web servers should allow access to their pages though the main domain unless a particular subdomain is required.

Succinctly, use of the www subdomain is redundant and time consuming to communicate. The internet, media, and society are all better off without it.

Using the links at the top of the page, you may view recently validated domains as well as submit domains for real-time validation.

Apache Webserver:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L] 

Windows Server/IIS: There is no way.

You can use Url Rewriter from Code Plex. With the same syntax.

RewriteCond %{HTTP_HOST} !^(www).*$ [NC]
RewriteRule ^(.*)$ http://www.%1$1 [R=301]

Source

like image 43
2 revs, 2 users 85% Avatar answered Nov 15 '22 14:11

2 revs, 2 users 85%