Search code examples
angularangular5angular-routing

Angular 5 routes don't work after deployment


In my Angular 5 application I've been running locally via ng serve and everything is working perfect. So then I did ng build -prod and uploaded the dist folder to my webserver.

The main page opens up and displays properly, but any of the routes that I try to go to result in a 404 error. I have no idea how to debug/fix this.


Solution

  • So first thing first, as discussed above you'll want to be sure to use the [routerLink] directive for your routing inside of the app. Using hrefs basically is telling your browser to navigate to a new route, and as a result will make a request to the server for the page and render out that new content (which is the reason why you're getting the 404, that route doesn't exist on the server, it's just being interpreted by your Angular application).

    The [routerLink] directive effectively updates the route inside of the application while updating the navigation history of the browser without actually fetching a new page. Older applications actually use a hashbang strategy while we're discussing a push state strategy... (Both discussed here if you're interested in learning more)

    Either way, like @Ritwick mentioned. At this point you'll want to redirect all server requests to your index.html that way if a user navigates to a route from outside of the application you can handle that. Just as some sample snippets you can do this redirection of routes if you're using NGINX:

    index index.html;
    
    location / {
      try_files $uri $uri/ /index.html;
    }
    

    Or if you're using something like Firebase you can update your firebase.json like so...

    {
      "hosting": {
        "public": "dist", // if your app is in a subfolder of the dist, include that
        "rewrites": [
          {
            "source": "**",
            "destination": "/index.html"
          }
        ]
      }
    }