代码之家  ›  专栏  ›  技术社区  ›  user979331

服务器上刷新时的角度2路由404

  •  0
  • user979331  · 技术社区  · 6 年前

    然后我将我的项目上传到一个apache服务器,现在我的路由不工作了,我可以转到index.html页面,该页面将我带到我的主页,我可以在我的站点[routerLink]=“['/register']”中导航,但是当我直接转到链接example.com/register时,我得到一个404错误,但是,当我转到example.com并单击[routerLink]=“['/register']”时,我需要转到example.com/register….为什么当我尝试直接转到页面时会收到404错误?

    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>
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Chellappan வ    6 年前

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