ASP.net MVC site : Redirect all “non WWW” request to WWW

旧街凉风 提交于 2019-12-03 00:34:53
Craig

Unfortunately, the URL rewrite module does not work with IIS6 (only IIS7 or greater). Have you considered creating your own HttpModule, something like this this?

IIS 6 how to redirect from http://example.com/* to http://www.example.com/*

Or you could potentially use a 3rd party solution like one of these:

http://iirf.codeplex.com/

http://www.urlrewriting.net/149/en/home.html

http://www.isapirewrite.com/

http://urlrewriter.net/

Tommy

You can do this from your web.config file

<system.webServer>
    <rewrite>
        <rules>
          <rule name="Redirect to WWW" stopProcessing="true">
            <match url=".*" />
            <conditions>
              <add input="{HTTP_HOST}" pattern="^example.com$" />
            </conditions>
            <action type="Redirect" url="http://www.example.com/{R:0}"
                 redirectType="Permanent" />
          </rule>
        </rules>
    </rewrite>
</system.webServer>

You could use config or Url Rewriter in IIS, but the best method I've found is just to put some code in Application_BeginRequest() in your global.asax.cs like this:

var HOST = "www.mydomain.com";

if ( !Request.ServerVariables[ "HTTP_HOST" ].Equals(
  HOST,
  StringComparison.InvariantCultureIgnoreCase )
)
{
  Response.RedirectPermanent(
    ( HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://" )
    + HOST
    + HttpContext.Current.Request.RawUrl );
}

Because you're doing this in code, you can have whatever logic you need on a per-request basis.

(IIS 7 or greater required)

from http://www.codeproject.com/Articles/87759/Redirecting-to-WWW-on-ASP-NET-and-IIS

(Similar to above solution, but not requiring you to add your own domain name.)

<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="WWW Rewrite" enabled="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" negate="true"
                            pattern="^www\.([.a-zA-Z0-9]+)$" />
                    </conditions>
                    <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}"
                        appendQueryString="true" redirectType="Permanent" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Note that you will most likely see squiggly lines under the tag with a message that the tag is invalid. I got this message but, in fact, it worked just fine.

If you want the intellisense to work, you can try this update here...

http://ruslany.net/2009/08/visual-studio-xml-intellisense-for-url-rewrite-1-1/

More information about httpRedirect can be found here...

http://www.iis.net/configreference/system.webserver/httpredirect

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