【问题标题】:404 on route refresh in angular 4, nginx server and apache404 角度 4、nginx 服务器和 apache 中的路由刷新
【发布时间】:2018-02-11 04:09:36
【问题描述】:

我在 Angular 4 中创建了一个新组件并添加了它的路由“帐户”。 当我运行ng serve 时,主页会打开,并且有一个指向帐户页面的链接。 单击帐户页面链接帐户页面打开。如果我刷新页面,它可以工作。

问题是当我使用ng build 构建并将构建上传到 apache 时。如果我点击“账户”链接,账户页面就会打开。 但是,如果我直接刷新或尝试打开帐户路由,我会收到 404 错误。

如果我添加“使用哈希”,那么它可以与“#”一起使用,但我不想要这个。

我正在使用 Angular 4.2.4

【问题讨论】:

  • 您需要做的就是修改您的 apache .htaccess 文件,以便所有请求都服务于 index.html 文件。进一步的路由由加载的角度脚本完成。

标签: angular


【解决方案1】:

您可以查看Link,了解如何在 Apache 上部署 Angular 应用程序。

如何在 apache 中服务 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>

【讨论】:

【解决方案2】:

尝试在你的 nginx 配置文件中添加 query_string

location / {
    alias /var/www/my_project/dist/;
    index index.html;
    try_files $uri $uri/ /index.html?$query_string;
}

【讨论】:

    【解决方案3】:

    在后端(服务器端)只需将所有 (404) 错误/无法识别的请求映射到您的索引(包括所有角度构建脚本)。然后它返回索引。在前端,你可以得到你需要的。它映射到你需要的页面。

    例如:- In spring Boot back-end this is an example answer

    【讨论】:

    • 您应该在回答中包含相关信息,以防帖子被删除。
    【解决方案4】:

    只需将它放在根目录下的 .htaccess 中

    重写引擎开启

    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    
    # Rewrite everything else to index.html
    # to allow html5 state links
    RewriteRule ^ index.html [L]
    

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 2021-05-20
      • 2018-09-20
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多