remove 'WWW' in ASP.NET MVC 1.0

前端 未结 4 1290
被撕碎了的回忆
被撕碎了的回忆 2021-02-11 04:14

I am attempting to force the domain name to not use the \'www\'. I want to redirect the user if attempted. I have seen very little on an MVC solution. Is there anyway to harness

相关标签:
4条回答
  • 2021-02-11 04:21

    Although I believe John Gietzen's answer is the most elegant solution, I was unable to implement do to a shared hosting environment. Determined to find a non-application driven solution I found this blog post which shows a good alternative method for IIS7. Thankfully DiscountASP.NET's has the URL Rewrite module available through the IIS Manager tool.

    Following this blog post on creating a rewrite rule any URL with www in the domain will do a permanent 301 redirect to the non-www site. All while preserving the full paths.

    Thanks for everyone's input.

    0 讨论(0)
  • 2021-02-11 04:30

    Implemented as an ActionFilter as that is MVC-like, and more explicit.

    public class RemoveWwwFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var req = filterContext.HttpContext.Request;
            var res = filterContext.HttpContext.Response;
    
    
            var host = req.Uri.Host.ToLower();
            if (host.StartsWith("www.")) {
                var builder = new UriBuilder(req.Url) {
                    Host = host.Substring(4);
                };
                res.Redirect(builder.Uri.ToString());
            }
            base.OnActionExecuting(filterContext);
        }
    }
    

    Apply the ActionFilter to your controllers, or your base controller class if you have one.

    For an introduction to Action Filters, see Understanding Action Filters on MSDN.

    [RemoveWwwFilterAttribute]
    public class MyBaseController : Controller
    
    0 讨论(0)
  • 2021-02-11 04:43

    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

    0 讨论(0)
  • 2021-02-11 04:45

    If you have control over the server, you should set up a virtual directory that accepts requests for "www.example.com" and permanently redirects (301) them to "example.com"

    While this may be possible in ASP.NET MVC, it is not ASP's job to do this sort of redirecting.

    On IIS: Virtual Directory

    On Apache:

    <VirtualHost *:80>
        ServerName www.example.com
        Redirect permanent / http://example.com/
    </VirtualHost>
    

    Both the IIS and the Apache settings will preserve the URL stem.

    0 讨论(0)
提交回复
热议问题