当我在localhost上运行我的angular 2项目时,我可以转到如下页面:localhost:4200 / register
然后我将项目上载到apache服务器,现在我的路线无法使用,我可以转到index.html页面,该页面将我带到我的主页,并且可以浏览我的网站[routerLink] =“ ['/ register']“,但是当我直接转到链接example.com/register时,出现404错误,但是当我转到example.com并单击[routerLink] =” ['/ register']“时,我到example.com/register ....为什么当我尝试直接转到页面时为什么出现404错误?
这是我的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 { }
这是我的.htaccess文件:
<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>
答案 0 :(得分:1)
原因是所有Angular2路由都应通过index.html文件提供。
这可以通过添加具有以下内容的.htaccess文件(在index.html所在的目录中)来实现。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.html [L]
</IfModule>
更多信息:https://github.com/angular/angular/issues/11884
也请检查此内容:https://github.com/mgechev/angular-seed/wiki/Deploying-prod-build-to-Apache-2