34

How can I add a route to the RouteConfig.cs file in an ASP.NET MVC 4 app to perform a permanent 301 redirect to another route?

I would like certain different routes to point at the same controller action - it seems a 301 would be best practice for this, specially for SEO?

Thanks.

niico
  • 11,206
  • 23
  • 78
  • 161
  • I guess this answer can be of some value http://stackoverflow.com/a/7664217/1236044 – jbl Jun 07 '13 at 09:24
  • possible duplicate of [How do you do a 301 permanant redirect route in ASP.Net MVC](http://stackoverflow.com/questions/2216890/how-do-you-do-a-301-permanant-redirect-route-in-asp-net-mvc) – JNF Dec 31 '13 at 09:53

2 Answers2

51

You have to use RedirectPermanent, here's an example:

public class RedirectController : Controller
{

    public ActionResult News()
    {

        // your code

        return RedirectPermanent("/News");
    }
}

in the global asax:

    routes.MapRoute(
        name: "News old route",
        url: "web/news/Default.aspx",
        defaults: new { controller = "Redirect", action = "News" }
    );
Bastianon Massimo
  • 1,710
  • 1
  • 16
  • 23
  • thanks - so this is automatically a permanent redirect? How would you tell it to be temporary? – niico Jun 07 '13 at 10:07
  • RedirectPermanent(url) add 301 as status code, Redirect(url) is a simple redirect – Bastianon Massimo Jun 07 '13 at 10:12
  • ahh so I have to create a controller? I can't just do all this from the RouteConfig.cs? (or global.asax) – niico Jun 07 '13 at 10:17
  • 2
    Yes, I'd suggest to add a new controller with all the redirects. If you add them to the MapRoutes you'll se the old url in the browser and the correct view (and this is not a redirect) – Bastianon Massimo Jun 07 '13 at 10:27
26

I know you specifically asked how to do this on the RouteConfig, but you can also accomplish the same using IIS Rewrite Rules. The rules live on your web.config so you don't even need to use IIS to create the rules, you can simply add them to the web.config and will move with the app through all your environments (Dev, Staging, Prod, etc) and keep your RouteConfig clean. It does require the IIS Module to be installed on IIS 7, but I believe it comes pre installed on 7.5+.

Here's an example:

<?xml version="1.0" encoding="UTF-8"?> 
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Redirect t and c" stopProcessing="true">
                    <match url="^terms_conditions$" />
                    <action type="Redirect" url="/TermsAndConditions" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
Jonas Stawski
  • 6,682
  • 6
  • 61
  • 106