Ramit DevOps architect, open source enthusiast, hobbyist writer.

Netlify redirect rules for Angular 7

Netlify redirect rules for Angular 7

One issue I faced when I tried to deploy my Angular 7 App to Netlify was broken routes. If you’re facing a similar issue, then in this post, I will try to help you fix that. 

So, say you have the following routes in your app,

const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'welcome', loadChildren: './welcome/welcome.module#WelcomeModule' }];

On your local it might work fine, i.e / and /welcome are accessible. However as soon as you deploy this to netlify, /welcome route will stop working. 

The reason for this behaviour is that, in the production build, an index.html file gets build that is bootstrapped to the angular code (whatever that is). So when you visit the domain, netlify serves you this index.html for the / route and things work fine. The problem starts when you hit the /welcome url or any other url for that matter. It gets served the page not found as shown below.

The issue occurs because netlify doesn’t know where to point the request for the /welcome page. To solve this, we need to tell netlify to reroute this request via the index.html, so that angular can take care of it. 

The way we do this is by adding a _redirect rule file to our project. 

  • Create a new file _redirect (no extension) in your src/ directory
  • Open up your angular.json and add this file to your asset array
  • Open the _redirect file and add the code below\ /* /index.html 200
  • The above code advises netlify to redirect all route requests (/*) via the index.html file (/index.html) and do so with a status code of 200
  • Deploy the changes and your broken routes should work

Please share if you find this post useful. Thank you for reading.

comments powered by Disqus