Deploy single page application Angular: 404 Not Found nginx

Melchia picture Melchia · Aug 24, 2017 · Viewed 31.7k times · Source

I Have an Angular application. I run the command ng build --prod --aot to generate the dist folder. In the dist folder I created a file named Staticfile then I uploaded the dist folder to pivotal.io with the following commands:

  1. cf push name-app --no-start
  2. cf start name-app

The app runs well. I have a nav bar, so when I change the path with navbar everything works fine. But when I do it manually (I enter the url myself) I have this error 404 Not Found nginx. This my app.component.ts:

const appRoutes: Routes = [
  { path: 'time-picker', component: TimePickerComponent },
  { path: 'material-picker', component: MaterialPickerComponent },
  { path: 'about', component: AboutComponent },
  { path: 'login', component: LoginComponent },
  { path: 'registration', component: RegistrationComponent },
  {
    path: '',
    redirectTo: '/time-picker',
    pathMatch: 'full'
  }
];

@NgModule({
  declarations: [
    AppComponent,
    TimePickerComponent,
    MaterialPickerComponent,
    DurationCardComponent,
    AboutComponent,
    LoginComponent,
    RegistrationComponent,
  ],
  imports: [RouterModule.forRoot(
    appRoutes
    // ,{ enableTracing: true } // <-- debugging purposes only
  ),
    FormsModule,
    BrowserAnimationsModule,
    BrowserModule,
    MdCardModule, MdDatepickerModule, MdNativeDateModule, MdInputModule

  ],
  providers: [{ provide: DateAdapter, useClass: CustomDateAdapter }],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(private dateAdapter: DateAdapter<Date>) {
    this.dateAdapter.setLocale('fr-br');
  }
}

Answer

Sven Dhaens picture Sven Dhaens · Jan 7, 2018

for those not using a Staticfile might wanna try this.

I had the same problem with nginx serving angular. The following is the default config file, probably found somewhere in /etc/nginx/sites-available/yoursite

     location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
    }

but what we acctually want is...

     location / {
            # First attempt to serve request as file, then
            # as directory, then redirect to index(angular) if no file found.
            try_files $uri $uri/ /index.html;
    }