Micah
Micah

Reputation: 116120

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

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, what's the best way to do it?

Thanks!

Upvotes: 2

Views: 3809

Answers (6)

Filix Mogilevsky
Filix Mogilevsky

Reputation: 777

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

    }
}

Upvotes: 0

Red Knight
Red Knight

Reputation: 289

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>

Upvotes: 2

Korayem
Korayem

Reputation: 12497

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.

IIS Remove WWW

Upvotes: 0

Micah
Micah

Reputation: 116120

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

Upvotes: 2

SLaks
SLaks

Reputation: 887469

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

Upvotes: 2

Dave Ward
Dave Ward

Reputation: 60580

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>

Upvotes: 7

Related Questions