Reputation: 11841
When I running my angular 2 project on localhost, I am able to goto a page like so: localhost:4200/register
I then uploaded my project to an apache server and now my routes are not working, I am able to goto the index.html page which brings me to my homepage and I am able to navigate thru my site [routerLink]="['/register']" but when I directly goto the link example.com/register I get a 404 error, but when I goto example.com and click on [routerLink]="['/register']" it takes me to example.com/register....why am I getting a 404 error when I try to goto the page directly?
Here is my app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from '../pages/home/home.component';
import { AuthGuard } from './auth/index';
import { LoginComponent } from '../pages/login/login.component';
import { LogoutComponent } from '../pages/login/logout.component';
import { ProfileHeaderComponent } from '../shared/user/profile-header/profile-header.component';
import { ProfileComponent } from '../pages/profile/profile.component';
import { RegisterComponent } from '../pages/register/register.component';
import { ForgotComponent } from '../pages/forgot/forgot.component';
import { UserComponent } from '../pages/user/user.component';
import { ListComponent } from '../pages/list/list.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'login',
component: LoginComponent
},
{
path: 'account',
component: ProfileComponent,
canActivate: [AuthGuard]
},
{
path: 'register',
component: RegisterComponent
},
{
path: 'forgot',
component: ForgotComponent
},
{
path: 'user/:username',
component: UserComponent
},
{
path: 'search/:type',
component: ListComponent
},
{
path: 'logout',
component: LogoutComponent
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Here is my .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) index.html [NC,L]
</IfModule>
Upvotes: 0
Views: 1439
Reputation: 27293
The reason is that all Angular2 routes should be served via the index.html file.
This can be achieved by adding a .htaccess file (in the same directory where the index.html resides) with the following contents.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.html [L]
</IfModule>
For More:https://github.com/angular/angular/issues/11884
Check this also:https://github.com/mgechev/angular-seed/wiki/Deploying-prod-build-to-Apache-2
Upvotes: 2