Angular 4.x – Add a 404 page

For a frontend application like Angular, the 404 page is served by the frontend application rather than the web server. To make this work, we should always return the index.html of our angular application for all applications, except for asset files.

Configure Server

When I first deployed my first Angular app in production, I quickly realized that it throws the 404 error when I directly visit a page other than the home page, for example, the /projects page. This is because there is only one HTML file, which is the index.html and the rest are asset files.

According to the Angular deployment documentation, we need to route all requests into index.html unless the requested file actually exists in the dist directory.

Here is a simple nginx configuration for that:

try_files $uri $uri/ /index.html;

It simply tries to serve the requested resource but when not found, it serves the index.html instead. Below is the full configuration.

server {
    listen 80;
    server_name example.com www.example.com;
    root /data/www/html/sites/example.com/dist;
    index index.html index.htm index.nginx-debian.html;
    location / {
        try_files $uri $uri/ /index.html;
        autoindex on;
    }
}

This way, when I visit /projects or /kung-fu, the nginx server will just serve the index.html file. Whether or not these routes actually exists now depends on the Angular application.

Add a 404 page Angular component

To handle 404 pages in Angular, we just need to make use of the ** routing path of Angular router and handle it with a 404 component.

src/app/app-routing.module.ts:

// Other imports...
import { NotfoundComponent } from './notfound/notfound.component';

const routes: Routes = [
  // Other routes...
  { path: '**',  component: NotfoundComponent },
];

// The rest of the routing module here...

Note the path and the component used. We will create the component later.

src/app/app.module.ts:

// Other imports...
import { NotfoundComponent } from './notfound/notfound.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  declarations: [
    // Other components
    NotfoundComponent,
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule { }

We also need to declare the component in our app module.

src/app/notfound/notfound.component.html:

<h1>Error 404</h1>
<p>Page not found</p>

src/app/notfound/notfound.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-notfound',
  templateUrl: './notfound.component.html'
})

export class NotfoundComponent { }

Restart the development server and we should have our 404 component working.

This entry was posted in Angular and tagged , , . Bookmark the permalink.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *