Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deploy single page application Angular: 404 Not Found nginx

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');
  }
}
like image 812
Melchia Avatar asked Aug 24 '17 10:08

Melchia


2 Answers

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;
    }
like image 178
Sven Dhaens Avatar answered Nov 18 '22 13:11

Sven Dhaens


In your nginx.conf file try using:

try_files $uri $uri/ /index.html;

instead of:

try_files $uri $uri/ =404;

That worked for me on Angular 5 project.

like image 24
Mad Javad Avatar answered Nov 18 '22 14:11

Mad Javad