繁体   English   中英

服务器上刷新时的Angular 2 Routing 404

[英]Angular 2 Routing 404 on refresh on server

当我在localhost上运行我的angular 2项目时,我能够转到如下页面:localhost:4200 / register

然后,我将项目上传到apache服务器,现在我的路线无法使用,我可以转到index.html页面,该页面将我带到我的主页,并且可以浏览我的网站[routerLink] =“ ['/ register']“,但是当我直接转到链接example.com/register时,出现404错误,但是当我转到example.com并单击[routerLink] =” ['/ register']“时,将以我为例。 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>

原因是所有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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM