Angular 2 路由无法使用 Apache 刷新页面

bom*_*lue 4 apache angular2-routing angular

使用带有更新的@angular/router 的 Angular 2 RC 4,我使用此问题中的答案在浏览器中显示了路由 URL

但是,当我刷新或直接请求使用非默认路由的页面时,它会将我带到默认页面(就像我请求 index.html 一样)而不是我想要的路由页面。如何使用 Apache 2.4 在页面刷新时使 Angular 2 路由正常工作?

路由和引导程序:

const routes: RouterConfig = [
{ path: '', redirectTo: 'dashboardTab', terminal: true },
{ path: 'dashboardTab', component: DashboardComponent },
{ path: 'missionTab', component: MissionComponent, children: childRoutes }];

bootstrap(NavbarComponent, [disableDeprecatedForms(), provideForms(),   provideRouter(routes), {provide: Window, useValue: window}, HTTP_PROVIDERS, ResponsiveState, {provide: PLATFORM_DIRECTIVES, useValue: RESPONSIVE_DIRECTIVES, multi: true}]).catch((err: any) => console.error(err));
Run Code Online (Sandbox Code Playgroud)

index.html 中的基本 href: <base href="/">

ima*_*era 10

基本上 apache 对您的 angular 应用程序路由一无所知,因此它在这里无能为力。

这里的技巧是让您的 apache 服务器index.html即使在找不到页面的情况下也能提供文件,以便 angular 可以渲染路由。

以下是步骤

  1. .htaccess在 angular applicaitonsrc文件夹中创建一个名为的文件,并将以下代码复制到其中

  RewriteEngine On
      RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
      RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
      RewriteRule ^ - [L]
  RewriteRule ^ /index.html

  1. 您需要将此.htaccess文件添加到assets您的数组中,angular.json以便 angulardist在您进行生产构建时将其复制到您的文件夹中。

  2. 最后在创建生产版本后,如果您将应用程序复制到 apache 服务器,一切都应该可以正常工作,但如果没有,您可能需要执行最后一步

进入/etc/apache2/apache2.conf你的服务器并修改

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>
Run Code Online (Sandbox Code Playgroud)

看起来像这样

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,您可能没有启用 mod 重写

sudo a2enmod rewrite
Run Code Online (Sandbox Code Playgroud)

请参阅 angular 团队的部署指南

https://angular.io/guide/deployment