Change the URL root path in ASP.NET MVC or IIS
Asked Answered
B

1

7

I'm working with a server with a custom URL: http://example.com/site/ and as you can see I need to change the default root path ("/") of my application to prevent 404 errors. Using IIS rewrite module with a outbound rule seems to work, with all html links and references being converted properly to query the internal website. The problem is when a Redirect() or RedirectToAction() method is used in my controllers, the internal name of the website is dropped so a 404 is caused. This is my IIS outbound rule:

<rewrite>
  <outboundRules>
    <rule name="Add path prefix to urls" stopProcessing="true">
      <match filterByTags="A, Form, Img, Link, Script" pattern="^/(.*)" />
      <action type="Rewrite" value="/site{R:0}" />
    </rule>
  </outboundRules>
</rewrite>

So to clarify: I have http://example.com/site/ when a redirection occurs to Account/Login, it becomes http://example.com/account/login instead of http://example.com/site/account/login . I guess the RouteConfig has to be tinkered with but I don't know how, or if I can do this in IIS. I have the following in my RouteConfig class:

routes.MapRoute(
    name: "SiteRoot",
    url: "site/{controller}/{action}",
    defaults: new { controller = "Home", action = "Index" }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Home", action = "Index" }
);

Thank you.

Burrstone answered 9/5, 2015 at 12:53 Comment(3)
why not just create a virtualdirectory called site under you website directory(www.example.com) and copy the code to there. It would work the way you wanted.?Abysmal
@Abysmal I can't, the server root is example.com/site/, If I create a virtual directory then I would have example.com/site/site/Burrstone
Have you got the answer yet? I also has the same issue when deploy my mvc react app onto IIS server, IIS will assign a virtual path for the application.Catboat
S
0

Assuming the issue is only with pages protected by the authorize annotation, you probably need to update the /App_Start/Startup.Auth.cs file to change the login path. You're looking for LoginPath = new PathString("/Account/Login"), which you'll change to LoginPath = new PathString("/site/Account/Login"),. In the MVC 5 starter site I tested in this was on line #28.

In my testing with your redirect rule and route configuration normal RedirectToActions worked fine, but if you're having trouble you might try removing the "Default" route mapping so that URL structure isn't selected by the router when trying to redirect.

Suziesuzuki answered 9/5, 2015 at 17:25 Comment(1)
Thanks for your answer. I need the /site/ root path for all the URLs, including images, scripts and static files in general. I can't use the ASP.NET routing in this files. RedirectToAction doesn't work with IIS outbound rules :(Burrstone

© 2022 - 2024 — McMap. All rights reserved.