Jamie Twells
Jamie Twells

Reputation: 2144

MVC - Make all URLs with a trailing slash 301 to URL without a slash?

Is there a way to redirect all URLs that end in a trailing slash to the url without?

Upvotes: 2

Views: 1210

Answers (1)

Jamie Twells
Jamie Twells

Reputation: 2144

In the Application_BeginRequest method in Global.asax, add the following:

if (HttpContext.Current.Request.Url.AbsolutePath != "/" && HttpContext.Current.Request.Url.AbsolutePath.EndsWith("/")) {
    string redirect = HttpContext.Current.Request.Url.AbsolutePath;
    redirect = redirect.Remove(redirect.Length - 1);
    Response.Clear();
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location", redirect);
    Response.End();
}

Upvotes: 2

Related Questions