开发者

How to remove the www. prefix in ASP.NET MVC

开发者 https://www.devze.com 2023-02-08 11:15 出处:网络
How do I remove the www. from incoming requests? Do I need to setup a 301 redirect or simply just rewrite the path? Either way开发者_如何学Python, what\'s the best way to do it?

How do I remove the www. from incoming requests? Do I need to setup a 301 redirect or simply just rewrite the path? Either way开发者_如何学Python, what's the best way to do it?

Thanks!


I believe it would be more appropriate to do that with IIS' URL rewriting module.

If you have access to IIS' management tool, there's a GUI to set up rewrite rules, in the "IIS" section of your site's settings. If you choose "Add Rule(s)..." from there (in the right column menu), choose the "Canonical domain name" rule in the SEO section to almost completely automate getting the rule set up.

If not, the rewrite rule would look like this in your web.config:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="CanonicalHostNameRule1">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^yourdomain\.com$" negate="true" />
                </conditions>
                <action type="Redirect" url="http://yourdomain.com/{R:1}" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>


You can handle the Application.BeginRequest event and check whether Request.Host starts with www.
If it does, call Response.RedirectPermanent, and pass a URL with the request's path and the naked domain.

You can construct the new URL by writing

"yourdomain.com" + Request.Url.PathAndQuery


I found a great solution here: http://nayyeri.net/remove-quotwwwquot-from-urls-in-asp-net

public class RemoveWWWPrefixModule : IHttpModule
{
    public void Dispose() { }

    private static Regex regex = new Regex("(http|https)://www\\.", RegexOptions.IgnoreCase | RegexOptions.Compiled);

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = sender as HttpApplication;
        Uri url = application.Context.Request.Url;
        bool hasWWW = regex.IsMatch(url.ToString());

        if (hasWWW)
        {
            String newUrl = regex.Replace(url.ToString(),
            String.Format("{0}://", url.Scheme));
            application.Context.Response.RedirectPermanent(newUrl);
        }
    }
}


You can use the following rewrite rule in the web.config file.

This rewrite rule will remove the WWW and also keep the trailing url and the initiating protocol.

    <rewrite>
       <rules>
          <clear/>
             <rule name="Canonical host name" enabled="true">
                <match url="(.*)"/>
                <conditions trackAllCaptures="true">
                    <add input="{HTTP_HOST}" negate="false" pattern="^www\.(.+)$"/>
                    <add input="{CACHE_URL}" pattern="^(.+)://" />
                </conditions>
                <action type="Redirect" url="{C:2}://{C:1}{REQUEST_URI}" appendQueryString="false" redirectType="Permanent"/>
             </rule>
       </rules>
    </rewrite>


This is more generic configuration as you can write it once in the URL Rewrite of the root IIS (not specific to a certain application pool) and it will automatically be applied to ALL your IIS websites without any dependency on your domain name.

How to remove the www. prefix in ASP.NET MVC


Much easier solution would be to create action filter and decorate your action with it.

public class RemovePrefix : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
                var url = filterContext.HttpContext.Request.Url.ToString().Replace("http://www.", "http://");
                filterContext.Result = new RedirectResult(url);

    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号