Search code examples
angulartypescriptangular-routing

Angular routing: Error when using direct path of a specified URL


I need some assistance with my routing setup in Angular. I am running on v12 of Angular.

I get a 404 Not Found error when trying to hit the direct URL for "register" in the following example URL: somesite.com/register.

I'm not sure whether this is a server or Angular issue. Here is my code for the router module:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { RegistrationPageComponent } from './registration-page/registration-page.component';

const routes: Routes = [
  { path: 'register', component: RegistrationPageComponent },
  // { path: 'register', redirectTo: '/register', pathMatch: 'full' }, // NOTE: I have tried this too
  { path: '', redirectTo: '/register', pathMatch: 'full' },
  { path: '**', redirectTo: '/register', pathMatch: 'full' },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

All other aspects of the routing work fine.

Thank you in advance!


Solution

  • To me it looks like your nginx server (if you are using one) does not reroute correctly. To handle this you have to change your nginx configuration files, which you can find here:

    Ubuntu 16.04+ / Debian 8+

    /etc/nginx/conf.d/default.conf
    

    CentOS 7 / Red Hat 7

    /etc/nginx/nginx.conf
    

    To rewrite all requests use this method to catch all URIs and forward them to your index.html:

    location / {
         root   /usr/share/nginx/html;
         index  index.html;
    
         try_files $uri $uri/ /index.html?$args;
    }
    

    If you want more complex rerouting behaviours or are using some other server configuration then at least you might know now what to look for.