Ben
Ben

Reputation: 1023

Redirect requests from an old website in MVC

I have built a website for a client using ASP.Net MVC 3, which was built to replace an old site that I did not build and was written in PHP.

Most of the pages I have on the new website map to an old one from the original, such as www.mysite.com/contactus used to be www.mysite.com/contactus.php

After reviewing my error logs (recorded by Elmah) I am getting errors for requests to some of the old pages, like this:

The controller for path '/ContactUs.php' was not found or does not implement IController.

Does anyone have a reccommendation on how to correct this issue, ideally to redirect the user to the new destination if it exists or perpahs just to default them to the home page.

Upvotes: 3

Views: 1217

Answers (2)

Wim Coenen
Wim Coenen

Reputation: 66723

You can use this route:

routes.MapRoute(
    name: "oldphp",
    url: "{*path}",
    defaults: new { controller = "PhpRedirect", action="Get" },
    constraints: new { path = @".*\.php" });

And then implement PhpRedirectController like this:

public class PhpRedirectController : Controller
{
    [HttpGet]
    public ActionResult Get(string path)
    {
        // TryGetNewUrl should be implemented to perform the
        // mapping, or return null is there is none.
        string newUrl = TryGetNewUrl(path);
        if (newUrl == null)
        {
            // 404 not found
            return new HttpNotFoundResult();
        }
        else
        {
            // 301 moved permanently
            return RedirectPermanent(newUrl);
        }
    }
}

Upvotes: 2

Ant P
Ant P

Reputation: 25221

You should be able to do this with an IIS rewrite rule in your web.config:

<rewrite>
  <rules>
    <rule name="Remove .php suffix">
      <match url="^(.*).php$" />
      <action type="Rewrite" url="{R:1}" />
    </rule>
  </rules>
</rewrite>

This should strip the '.php' suffix on any incoming request. See here for more information: http://www.iis.net/learn/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module

Upvotes: 4

Related Questions