asp.net mvc: How to redirect a non www to www and vice versa

爷,独闯天下 提交于 2019-11-26 06:05:38

问题


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\\.domain\\.com\" /> 
</conditions> 
<action type=\"Redirect\" url=\"http://domain.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.


回答1:


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.




回答2:


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\.domain\.com" /> 
        </conditions> 
        <action type="Redirect" url="http://domain.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.

EDIT:

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.




回答3:


    **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();
        }
    }



回答4:


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);
    }
}



回答5:


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.YourSite.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();
        }
    }



回答6:


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>



回答7:


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
        }
    }


来源:https://stackoverflow.com/questions/3197319/asp-net-mvc-how-to-redirect-a-non-www-to-www-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!