Search code examples
angularangular-routingangular-router

How does Angular routing take precedence over file paths on a static site


If I build a static site with the file structure:

-index.html
-blog/index.html

And I put an Angular app with routing inside blog/index.html, then go to the route example.com/blog/page/2, it goes to the correct blog page within the Angular application. In a sense, it opens /blog/index.html, and processes /page/2 within the Angular application.

How?

Why doesn't Apache (or Nginx) take precedence over that, and try to open /blog/page/2/index.html, and not finding it, show a 404?

I think it's pretty awesome that it can work like this, but I can't figure out how it's technically possible.


Solution

  • apache or nginx or whatever your web server is needs to be properly and intentionally configured to serve an angular app. There are countless guides for various web server configs, but generally you will configure any 404 error to redirect to the project root index.html page. In the event of a REAL 404 however, your angular app should be set up to handle it properly.

    This is for initial page load or refresh ONLY. Once the angular app is up and running, it's a moot point because angular intercepts and handles all navigation so it doesn't hit your web server again. The angular router just calls up the files it needs and uses the browser history API to push items into your web history to simulate normal navigation. They're called Single Page Applications because there is actually only a single page ever served from your web server, the rest is all tricks / simulation.