在 ng build in Angular 2 Cli application build 刷新后显示 404 Error

After ng build in Angular 2 Cli application build the refresh shows 404 Error

我已成功创建并 运行 angualr2-cli 应用程序。我还在 apache 服务器上部署了应用程序,为此我使用了 angular2-cli 命令的帮助 ng build

但是我的应用程序在刷新子页面时出现故障(404 页面未找到错误)。

请按照以下步骤进行操作,您会发现我提到的问题。

  1. Click this link to load the web page

  2. 现在单击作业边栏菜单或任何边栏元素

  3. 然后刷新页面

你会看到我的问题。页面消失并显示 404 错误。为什么它在部署到 apache 服务器后发生。当我使用 ng serve 命令

运行 连接服务器时,刷新在开发环境 (http://localhost:4200 ) 上完美运行

我已经在 this guide 之后解决了这个问题。这在我的配置中没有错。问题是在服务器设置上添加 .httaccess 和允许重写规则。

我总结了解决此问题的步骤。

  1. 我在 index.html 所在的位置添加了 .httaccess 文件。

    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.html [L]
    </IfModule>
    

2.Then 允许使用 sudo a2enmod rewrite

在 apache 服务器上重写 mod

3.The重启apache服务器service apache2 restart

4.After 打开 /etc/apache2/sites-enabled/000-default.conf 文件并在 <VirtualHost> 标签上添加以下规则

<Directory "/var/www/html">
   AllowOverride All
</Directory>

就是这样!!任何链接都重定向到我的 index.html 并且有效。因为在 angular2 routing

中所有的路由都是来自 index.html 的路由

这是 IIS 服务器的解决方案

  1. 创建 web.config 包含以下内容的文件:

     <!-- configure the site to work with HTML5 push state -->
    <rewrite>
      <rules>
        <rule name="AngularJS Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
    

  2. 将此文件放入您的根部署文件夹中。