angularangular-routingangular9angular-builder

Angular - After Build Inner Routing Not Working - 404 Error


I am using Angular 9.0 and everything is working fine in ng serve -o mode but when i try to build the project using ng build i can only view the root page. When i try to go to any other page it returns 404 error something i am not experiencing in local ng serve mode. Any clues on how to fix the issue?

So http://www.example.com/ << this page opens fine but http://www.example.com/dashboard returns 404

Edit: In order to test difference scenarios, to see what might be causing the problem I have managed to identify the issue. Navigation works fine if I use routerLink, but it doesn't work if I use href or window.location.href. Any idea why it would crash when using href or window.location.href ?


Solution

  • ng serve automatically takes care of URL redirects to the index.html.

    The following addition in your app.module.ts should solve your problem.

    import { PathLocationStrategy, LocationStrategy } from '@angular/common';
    
    ...
    
    providers: [ { provide: LocationStrategy, useClass: PathLocationStrategy } ]
    

    https://angular.io/api/common/PathLocationStrategy

    Edit:

    href is the default attribute provided by browsers for navigating (switching) between pages, where the entire page will be get re-loaded losing the current state.

    A more detailed explanation on href vs routerLink.

    So if you are hosting your files on a Apache server it tries to find a index.html file inside the /dashboard directory which doesn't exist, thus the 404 error. To solve this you'll have to rewrite all your traffic back to index.html. A more detailed explanation on rewrites.