asp.net MVC: How to redirect a non www to www and vice versa
Asked Answered
L

9

49

I would like to redirect all www traffic to non-www traffic

I have copied this into my web.config

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

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

per this post

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

but I got a 500 internal server error.

Linolinocut answered 7/7, 2010 at 17:32 Comment(0)
F
84

You might consider a different approach:

protected void Application_BeginRequest (object sender, EventArgs e)
{
   if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
   {
      UriBuilder builder = new UriBuilder (Request.Url);
      builder.Host = "www." + Request.Url.Host;
      Response.Redirect (builder.ToString (), true);
   }
}

This will however do a 302 redirect so a little tweak is recommended:

protected void Application_BeginRequest (object sender, EventArgs e)
{
   if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
   {
      UriBuilder builder = new UriBuilder (Request.Url);
      builder.Host = "www." + Request.Url.Host;
      Response.StatusCode = 301;
      Response.AddHeader ("Location", builder.ToString ());
      Response.End ();
   }
}

This one will return 301 Moved Permanently.

Finland answered 7/7, 2010 at 17:52 Comment(9)
does this approach work in MVC? Your way is how I do it in Web Forms, but I think the MVC Routing Framework is dealt with differently.Necessary
I took a very similar approach. See #2176475Khrushchev
@rockinthesixstring: It works in MVC. It kicks in very early so it doesn't matter much whether MVC or WebForms is going to be processing the request afterward.Finland
request can also be Request.Headers["x-forwarded-host"];Valladares
Since .NET 4.0 there is Response.ResponsePermanent method which makes the code simpler than setting headers manuallyDavid
@jakubka: I think you actually meant to type Response.RedirectPermanent. Your link is correct though.Monarchal
Why the !Request.Url.IsLoopback part?Secundine
This solution, being a code based one, was much quicker to implement than web.config option which relies on HTTP Redirect module being installed on server, meaning no IIS downtime. Very usefull thanksAutobus
Thanks. I used this piece of code for a while, but I've moved the logic into the Rewrite sections of the web.config so that all of my rewrite rules are in one place. Requires the URL Rewrite IIS module though.Multivocal
N
14

if you copied it directly then you have incorrect markup in your web.config

you need

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

The line that says

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

is stating that you need to put the config in that location within your web.Config. <system.webServer> is one of the configSections of your web.Config file.

Make sure you first have the URL Rewrite module installed for IIS7

The page above talks about redirecting HTTP to HTTPS, but the concept still applies for WWW to non WWW

Also, here is some detailed information on how it all comes together.

Necessary answered 7/7, 2010 at 17:47 Comment(3)
ok..i have done this and it says <rewrite> is not a valid tagLinolinocut
I edited my answer. I'm still looking how to make it so that Visual Studio doesn't yell at you, but it should work for IIS7Necessary
@ChaseFlorell - would it be better to use the IIS7 URL Rewrite module or the .Net routing functionality within the webApp iself to do a redirection if you have the ability to use both? Or (third option) should I just respond to both and maintain URL for both using a reverse proxy in the URL Rewrite module? ...although that last 3rd option is not ideal for SEO I would think.Ankle
C
8
    **For a www to a non www Thanks @developerart**

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Url.Host.StartsWith("www") && !Request.Url.IsLoopback)
        {
            UriBuilder builder = new UriBuilder(Request.Url);
            builder.Host = Request.Url.Host.Replace("www.","");
            Response.StatusCode = 301;
            Response.AddHeader("Location", builder.ToString());
            Response.End();
        }
    }
Cumbrous answered 17/4, 2012 at 15:20 Comment(0)
S
5
protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (!this.Request.Url.Host.StartsWith("www") && !this.Request.Url.IsLoopback)
    {
        var url = new UriBuilder(this.Request.Url);
        url.Host = "www." + this.Request.Url.Host;
        this.Response.RedirectPermanent(url.ToString(), endResponse: true);
    }
}
Sickness answered 25/10, 2013 at 22:56 Comment(0)
S
4

You can use for https and www redirect. (You need to change "example")

<system.webServer>
  <!-- For force ssl and www -->
  <rewrite>
    <rules>
      <!-- For force ssl -->
      <rule name="http to https" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTPS}" pattern="^OFF$" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
      </rule>
      <!-- For force ssl -->
      <!-- For force www -->
      <rule name="redirect to www" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTP_HOST}"  pattern="^example\.com$" />
        </conditions>
        <action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" redirectType="Permanent" />
      </rule>
      <!-- For force www -->
    </rules>
  </rewrite>
  <!-- For force ssl and www -->
</system.webServer>
Spread answered 26/1, 2018 at 12:16 Comment(0)
D
3

Building on user 151323' answer, here the complete answer for Azure users who also want to prevent users from accessing the site from a azurewebsites.net subdomain (this goes into your Global.asax inside the main class (MvcApplication for MVC users)):

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Url.Host.StartsWith("YourSite.azurewebsites") && !Request.Url.IsLoopback)
        {
            Response.StatusCode = 301;
            Response.AddHeader("Location", "www.example.com");
            Response.End();

            return;
        }

        if (!Request.Url.Host.StartsWith("www") && !Request.Url.IsLoopback)
        {
            UriBuilder builder = new UriBuilder(Request.Url);
            builder.Host = "www." + Request.Url.Host;
            Response.StatusCode = 301;
            Response.AddHeader("Location", builder.ToString());
            Response.End();
        }
    }
Dispersal answered 10/8, 2013 at 9:25 Comment(0)
H
1

I know this thread is ancient and seems to be answered to death. But it may be useful to wrap everyone's global.asax suggestion with a check whether you are working locally or not. That way during development using IIS Express your site will not try and redirect to a 'www' sub-domain.

Something along the line of:

protected void Application_BeginRequest(
        object sender,
        EventArgs e)
    {
        if (!Request.IsLocal)
        {
            // Do your check for naked domain here and do permanent redirect
        }
    }
Horizon answered 5/7, 2015 at 16:26 Comment(0)
C
0

You can achieve redirect non www to www at Server Level as well in IIS by writing the rule.

This rule will work but please note this rule will only work if you have installed URL Rewrite on your IIS Server. If URL Rewrite is not installed on your IIS Server then this rule will not work.

In order to install URL Rewrite on your server then go to this official website link and download the extension on your server and install it. After that restart the IIS Server and it will work.

URL Rewrite Extension Official Website Link: https://www.iis.net/downloads/microsoft/url-rewrite

<rewrite>
            <rules>
                <rule name="Redirect example.com to http://www.example.com HTTP" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url=".*"></match>
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example.com$"></add>
                        <add input="{HTTPS}" pattern="off"></add>
                    </conditions>
                    <action type="Redirect" url="http://www.example.com/{R:0}" redirectType="Permanent" appendQueryString="true"></action>
                </rule>
            </rules>
        </rewrite>
Caloric answered 11/5, 2021 at 8:10 Comment(0)
K
0

IIS can do it for you automatically:

Select site > URL rewrite > Add rule(s) > Canonical domain name

Choose primary domain and it is finished.

(If you do not have URL rewrite module installed, install it: https://www.iis.net/downloads/microsoft/url-rewrite)

Kenyatta answered 3/12, 2021 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.