Why when i refresh an angular application results to 404 Not Found?

5/29/2021

I am working on an angular application and deployed it in kubernetes. I can access my application through Nginx Ingress.

I am using angular router to enable navigation through different components in my app.

Using the deployed application i tried to navigate through different components, when I click refresh on the browser or directly access a specific url path, I get 404 Not Found Page.

For example, if one accesses URL mycompany.domain.com, it shows the home component. In my angular router I have a /user path that points to user component.

Upon navigating to user menu, my new URL will now be mycompany.domain.com/user - and it is all working as expected. However if I refresh the current page, it will become 404 Not Found Page, which is the problem.

My few thoughts:

  1. The router is part of the SPA, and of course will be loaded once the SPA is loaded.
  2. The url path /user is only known by the router in the SPA - and so when we try to access the mycompany.domain.com/user directly, the server does not find any resource matching to it.
  3. The only one who can understand the /user url path is my SPA - which is not loaded yet because the server already decided that the resource is not found.

So I concluded (but still to try) the problem can occur anywhere I deploy my SPA regardless my ingress or server configuration.

My solution is using angular router useHash option - it means that my navigation path will be after a # and be considered as URL Fragments, like this: mycompany.domain.com/#/user, in this case, my server will not try to understand the fragment, as it is meant to be understood by the page. I did so inspired by Vue.js router.

My questions are:

  1. Is my understanding (and conclusion) correct?
  2. Is there any other solution? Because Angular by default doesn't use the hash and I am sure that there is a reason for that because it is not making sense if its doesn't work when deployed?
  3. Can URL Rewriting help me? I have tried to look for it myself the usage is not matching with my conclusions.

I am not a SPA expert, I am just starting and I would appreciate if someone will correct and answer me.

-- Azel
angular
kubernetes
nginx

1 Answer

5/29/2021

Save This code as web.config then paste the web.config file in the dist folder

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.web>
    <compilation targetFramework="4.0" />
    <customErrors mode="On" redirectMode="ResponseRewrite">
      <error statusCode="404" redirect="/index.html" />
    </customErrors>
  </system.web>
  <system.webServer>
    <httpErrors errorMode="Custom">
      <remove statusCode="404"/>
      <error statusCode="404" path="/index.html" responseMode="ExecuteURL"/>
    </httpErrors>
  </system.webServer>
</configuration>
-- Uchchas
Source: StackOverflow