MVC 3 SEO Friendly URLs
Continuing on from my previos article on adding a xml sitemap, today we will be looking at adding seo friendly urls to MVC 3.
Rather than re-inventing the wheel here I would instead redirect you to this awesome article. One of the reasons I like this article is it still gives you the ability to use our database indexes since we are still getting our products by their primary key.
The only thing I would add to the article is the ability to redirect mysite.com/Product/1/RandomString to mysite.com/Product/1/Product-Name since we already know what product the user is trying to access if the typo is in the product name. This is also handy if you have already deployed your website with the previous routes.
string expectedName = product.Name.ToSeoUrl();
string actualName = (productName ?? "").ToLower();
// permanently redirect to the correct URL
if (!string.Equals(expectedName, actualName))
{
return RedirectToActionPermanent("Details", new { productName = expectedName });
}
Now all we need to do is update our MVCSiteMapProvider from before:
var node = new DynamicNode();
node.Title = product.Name.ToSeoUrl();
node.RouteValues.Add("id", product.Id);
I’m not sure if this is useful, but, if you don’t need to redirect for any other purpose than SEO you can instead use:
This will reduce un-necessary server load and also give you the ability to have custom inbound pages all related to product 1, but attributing the SEO juice to the proper originating page.
Oops!
You can instead use:
link rel=”canonical” href=”http://mysite.com/Product/1/Product-Name”