Angular Js

How to Handle 404 error on refreshing Angular Inner Pages at Production

How to Handle 404 error on refreshing Angular Inner Pages at Production

Handle 404 error on Refresh

This Article helps you to Understand, How to Handle 404 error on refreshing Angular Inner Pages at Production


Using ng build —prod, you have developed an Angular application. The production server is where you deploy it.Up until you reload the page, everything functions as it should.

The app throws A message stating that the requested URL was not present on this server (Status code 404 not found).
If you reload the page or copy and paste url to another tab / browser, it seems like angular routing is not functioning on the production server.


Since Angular 2 applications by default don't prefix their URLs with a hash (#), trying to access a deep link directly or refreshing an internal page may result in a 404 page not found message. Because the angular section of the url corresponds to a route in your angular application and must be processed in the client browser, the web server receiving the request looks for a resource matching the entire url on the server, which doesn't exist.


The error appears on the following scenarios

  • When you type the URL directly in the address bar.
  • When you refresh the page
  • The error appears on all the pages except the root page.
  • The error occurs only if you are using HTML 5 Routing or PathLocationStrategy


Reason for the requested URL was not found on this server error
Every time a page needs to be displayed in a multi-page online application, a request must be sent to the web server.
Either type the URL into the address box or select the Menu link or button to do it.
Every time you take such a step, the Web server receives a fresh request.
A comparable page must be present on the server for each request.
That page is located by the server, which then sends it back to the client.

However, in Angular Apps, the app launches as soon as the home page (index.html) loads.
Any additional requests just partially load the page rather than reloading it.
Requests are processed by the Angular router on the client side rather than being routed to the server.
The article regarding the Angular bootstrap process has further information.


When Error Occurs

As an illustration, the server receives a request for example.com and responds with index.html. Thus, Angular will be bootstrapped.
Now, when you click on example.com/faq, the Angular Router handles the request client-side rather than sending it to the server. The component linked to the faq route is loaded by the router. The faq component may send an HTTP request to fetch the faq content to display. But the request to display the faq page is never sent to the server.

What occurs when a user refreshes the page or types example.com/faq into the address bar. Now the server receives the request to get the faq content page. Since the server does not have a faq page, it returns the There was a 404 error or the requested URL could not be found on this server.



There are multiple approaches or strategy to sort this issue
1. By rewriting all virtual urls depends on the Server it is Hosted

2. At Angular Level we can use 2 Approaches
PathLocationStrategy (or html5Mode)
HashLocationStrategy


Approach 1: By rewriting all virtual urls depends on the Server it is Hosted

A. in Case of Linux Hosting with Apache Server
Add .htacces files at root of your website, with following code

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        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]
    </Directory>
</VirtualHost>


B. in Case of Windows Hosting with IIS Server
Add .web.config files at root of your website, with following code

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



C. in Case of nginx
Add following code

server {
    server_name my-app;
    root /path/to/app;
    location / {
        try_files $uri $uri/ /index.html;
    }
}



Approach 2: Using Angular Approaches
A. PathLocationStrategy (or html5Mode) - in app.module.ts file

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    bootstrap: [AppComponent],
})
export class AppModule {}


B. HashLocationStrategy
We can do it while registering your root with RouterModule. You can pass a second object with property useHash:true. in app.module.ts file

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { ROUTES }   from './app.routes';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    RouterModule.forRoot(ROUTES ,{ useHash: true }),],
    providers: [],
    bootstrap: [AppComponent],
})
export class AppModule {}

If you simply need something to operate right away, this is the most straightforward method. Stick with the default unless you have a compelling need to use hash routes, anuglar.io advises.






Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram