I have a very simple project that has the following routing.
const routes: Routes = [
{ path: "start", component: StartComponent },
{ path: "sub01", component: Sub01Component },
{ path: "", redirectTo: "/start", pathMatch: "full" },
{ path: "**", component: StartComponent }
];
When I run it locally using ng serve
and browsing to localhost:4200, I get to see the starting page's contents and the URL is rewritten to localhost:4200/start, just as expected. Then, I produced a semi-final version by ng build and put in the dist directory on my IIS. Browsing to the address of the application produces the same result as above. I can also confirm that browsing to e.g. the images' URLs produces the expected result too.
The difference, as I noticed, is that locally, it works to reload the page (i.e. surfing to localhost:4200/start) while the same operation on the remote fails, giving me 404 (so surfing to http://address.that-worked-just.now/start works not). Since I can access other URLs than just the root, it seems to me that it's only the routing that won't work.
I'm a bit flabbergasted by this behavior and not sure how to diagnose it further. The only difference I'm aware of within my reach is that locally, I serve the app using the default Angular CLI while on the remote, I have IIS that serves index.html containing the script. So I figure that once the document is produced to the client, everything else happens on the client. (The app is really limited and there's no interaction with the server, no services etc. as it's basically a landing page, at least for now).
Am I missing something that should be declared in any of the config files? Or is it a weird misbehavior likely to occur due to some firewall policy or such? I'm not sure how to determine that and I rather assume that I've done something stupid than blame the server team. Given the description above, what more can be inferred?
IIS has its own routing system. So when we host Angular in IIS, Angular routing will be failed, because IIS doesn’t understand the Angular routing and will be looking for a resource that matches the route and it gives you 404 error.
To resolve the issue you could try one of the below solutions:
Use the IIS URL rewrite rule to set the routing:
<system.webServer>
<rewrite>
<rules>
<rule name="Angular Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
Source: https://angular.io/guide/deployment#fallback-configuration-examples
Another way is to add the error page for 404 to redirect to /index.html.