html - HTML5 模式下的 NGINX、proxy_pass 和 SPA 路由

标签 html angular nginx

我将 NGINX 设置为 docker 容器虚拟网络的反向代理,该虚拟网络将自身作为容器运行。其中一个容器以 HTML5 模式为基于 Angular 4 的 SPA 提供客户端路由服务。

应用程序映射到位置/在 NGINX 上,因此 http://server/将您带到 SPA 主屏幕。

server {
    listen 80;

    ...

    location / {
        proxy_pass http://spa-server/;
    }

    location /other/ {
        proxy_pass http://other/;
    }

    ...
}

Angular 路由器将 URL 更改为 http://server/home或在 SPA 内导航时的其他路线。

但是,当我尝试直接访问这些 URL 时,返回了 404。此错误源自 spa-server,因为它显然没有这些路由的任何内容。

我找到的配置 NGINX 以支持这种情况的示例始终假定 SPA 的静态内容直接从 NGINX 提供,因此 try_files 是一个可行的选项。

如何将任何未知的 URL 转发到 SPA 以便它自己处理它们?

最佳答案

对我有用的解决方案是将指令 proxy_intercept_errorserror_page 添加到 NGINX 中的 location/:

server {
    listen 80;

    ...

    location / {
        proxy_pass http://spa-server/;
        proxy_intercept_errors on;
        error_page 404 = /index.html;
    }

    location /other/ {
        proxy_pass http://other/;
    }

    ...
}

现在,每当请求未知 URL 时,NGINX 将返回/index.html,即来自 spa-server 的 SPA。尽管如此,该 URL 仍可供 Angular 使用,路由器将立即在 SPA 中解析它。

当然,现在 SPA 负责处理“真正的”404。幸运的是,无论如何这在 SPA 中不是问题和良好实践。

更新:感谢@dan

关于html - HTML5 模式下的 NGINX、proxy_pass 和 SPA 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45502403/

相关文章:

javascript - FullCalendar 未显示在 Asp.Net Core Razor View 中

html - 悬停时CSS消失

angular - Ionic 2/Angular 2 Alert 作为带有 Nav 的服务

html - 带边距的 CSS 布局表

html - 悬停溢出的文本在 <a> 内不对齐

angular - 处理http.get()中的错误

angular - 加载 md-table( Angular Material 设计表)时出错

ssl - 将额外的子域附加到当前由 Certbot 创建的 Let's Encrypt SSL 证书

node.js - "Cannot GET"从 Nginx 反向代理到 express.js 上的 socket.io

nginx - 错误 : "Failed to process connection. Reason: The object was used after being disposed." with nginx, fastcgi-mono-server4 和 ServiceStack