Angular 2+ Getting 404 - File or directory not found error on browser refresh for pages other than Home Page URL after hosting

Updated on: September 27, 2019

When you are running any Angular 2 plus App on browser after hosting it on any server like IIS, Apache on any hosting provider like GoDaddy and getting the below error, then read the following solution to fix the issue that you are getting after publishing your website:

Error:

404 - File or directory not found.

The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

Solution:

It is clear that there is no issue with your Angular App and there is no change required in your existing Angular App, the change that is required is to enable URL refreshing on your hosting server. 

So basically what caused this issue to come, the answer is: You have hosted your site on IIS / Apache server and when you visited any page other than your Home page, what IIS & Apache will do internally is that it will search for the file in your hosted directory and if it does not find the file on that location, then it will give this 404, file or directory not found error. So you need to add fallback route configuration in the root location of your hosted website. So now, add the following required changes based on your hosting server:

IIS (Internet Information Service) Hosting Server:

We need to add following web.config file on the root location where your Angular App is hosted, once you add this rewrite rule, it will fix your browser refresh issue when visiting any URL other than home page URL of your website.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularPageRefresh" 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="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Apache Server (for PHP website):

We need to add following .htaccess file on the root location where your Angular App is hosted, once you add this rewrite rule, it will fix your browser refresh issue when visiting any URL other than home page URL of your website.

<IfModule mod_rewrite.c>
    RewriteEngine on

    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]

    # Rewrite everything else to index.html
    # to allow html5 state links
    RewriteRule ^ index.html [L]
</IfModule>

Once you add above rewrite rule configuration file on the root location of hosted website, then it should fix your 404 file or directory not found issue of your Angular 2, Angular 4, Angular 6, Angular 8 + website.