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

8

16

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

Schuller answered 6/2, 2009 at 19:28 Comment(5)
This is called the "canonical name" if you wish to look it up elsewhere.Greenstone
It's important to be aware that if you don't use a www (or some other subdomain) then all cookies will be submitted to every subdomain amd you won't be able to have a cookie-less subdomain for serving static content thus reducing the amount of data sent back and forth between the browser and the server. Something you might later come to regret: twitter.com/codinghorror/statuses/1637428313Shelled
@Diodeus - Do we really need a tag for that?Jyoti
Correction: .htaccess is completely unrelated to PHP, it's an Apache server feature and works whatever language you're using on Apache.Infatuation
possible duplicate of Route www link to non-www link in .net mvcLichen
W
6

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.

Weisler answered 6/2, 2009 at 21:25 Comment(0)
L
27

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>
Locris answered 6/2, 2009 at 19:30 Comment(2)
Actually the problem is I am on godaddy's shared hosting server, where I don't have access to modify IIS settings. :( That's why I am asking a procedure through ASP.NET, <meta> tags, etc.Schuller
perhaps I'm missing something, but your accepted answer requires you to modify web.config. My answer also requires you to modify web.config.Locris
W
6

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.

Weisler answered 6/2, 2009 at 21:25 Comment(0)
M
5

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>
Marindamarinduque answered 9/4, 2009 at 20:59 Comment(2)
When I try this rule with the redirect to "www.{HTTP_HOST}/{R:1}", nothing happens. If I change "{HTTP_HOST}" to the actual domain name, it works. Is there something else I need to change so the rule works using "{HTTP_HOST}?" Thanks.Meadowsweet
Is the condition and action written exactly the same?Marindamarinduque
O
2

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

Oldfangled answered 6/2, 2009 at 19:29 Comment(0)
W
0

This is usually handled by your web server directly in the configuration. As you mentioned, the .htaccess file does this for the Apache web server -- it has nothing to do with PHP. Since you're using ASP, it's a near certainty your server is IIS. I know there is a way to set up this direct with IIS, but I don't know what it is. You may be aided in your search by knowing you should be googling for things related to "IIS redirect", not "ASP redirect".

That said, you CAN do it in PHP, and almost certainly ASP as well, but you'll have to have hitting any URL at the wrong domain invoke an ASP script that performs the redirect operation (using appropriate API calls or by setting headers directly). This will necessitate some URL rewriting or somesuch on the part of the server so that all URLs on the wrong host are handled by your script... just do it directly at the server in the first place :)

Warmhearted answered 6/2, 2009 at 19:35 Comment(0)
A
0

We did this on IIS 6 quite simply. We essentially created a second virtual server that had nothing on it than a custom 404 page .aspx page. This page caught any requests for WHATEVERSERVER.com/whateverpage.aspx and redirected to the real server by changing the URL to be www.whateverserver.com/whateverpage.aspx.

Pretty simple to setup, and has the advantage that it will work with any domains that come in to it (if you have multiple domains for instance) without having to setup additional rules for each one. So any requests for www.myoldserver.com/xxx will also get redirected to www.whateverserver.com/xxx

In IIS 7, all this can be done with the URL writing component, but we prefer to keep the redirects off on this virtual server.

Alternator answered 6/2, 2009 at 19:42 Comment(1)
Actually the problem is I am on godaddy's shared hosting server, where I don't have access to modify IIS settings. :( That's why I am asking a procedure through ASP.NET, <meta> tags, etc.Schuller
C
0

In case you are using IIS 7, simply navigate to URL rewrite and add the canonical domain name rule.

P.S. Its to make sure that you get redirected from domain.com to www.domain.com

Carrie answered 27/1, 2011 at 12:43 Comment(0)
S
0

This version will:

  1. Maintain the http/https of the incoming request.
  2. Support various hosts in case you need that (e.g. a multi-tenant app that differentiates tenant by domain).

<rule name="Redirect to www" stopProcessing="true">
  <match url="(.*)" />
  <conditions trackAllCaptures="true">
    <add input="{CACHE_URL}" pattern="^(.+)://" />
    <add input="{HTTP_HOST}" negate="true" pattern="^www\.(.+)$" />
  </conditions>
  <action type="Redirect" url="{C:1}://www.{HTTP_HOST}/{R:1}" />
</rule>
Stevie answered 8/3, 2017 at 23:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.