【问题标题】:NGINX, proxy_pass and SPA routing in HTML5 modeHTML5 模式下的 NGINX、proxy_pass 和 SPA 路由
【发布时间】:2017-08-04 08:56:40
【问题描述】:

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

应用程序被映射到 NGINX 上的位置 /,以便 http://server/ 将您带到 SPA 主屏幕。

server {
    listen 80;

    ...

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

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

    ...
}

在 SPA 中导航时,Angular 路由器会将 URL 更改为 http://server/home 或其他路由。

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

我发现的配置 NGINX 以支持此场景的示例始终假定 SPA 的静态内容直接从 NGINX 提供,因此try_files 是一个可行的选择。

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

【问题讨论】:

    标签: html angular nginx


    【解决方案1】:

    对我有用的解决方案是将指令 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。尽管如此,Angular 仍然可以使用 URL,并且路由器会立即在 SPA 中解析它。

    当然,现在 SPA 负责处理“真正的”404。幸运的是,无论如何,这在 SPA 中都不是问题,也是一个很好的做法。

    更新:感谢@dan

    【讨论】:

    • 这确实返回了 index.html 的 404 内容。但它也返回 404 状态码。我设法使用error_page 404 = /index.html 解决了这个问题(注意=
    • 我遇到了同样的问题(尽管使用的是 Elm SPA),您的回答以及 Dan 的评论帮助很大。非常感谢。
    • 我已经尝试实现这个,但是错误页面试图从 /usr/share/nginx/html/index.html 而不是从 proxy_pass url 加载。
    • 看起来这只能在 / 的位置内工作,但我的需要是这样的: location /some-path/ {
    • 搞定了,错误页面也需要路径:例如error_page 404 = /some-path/index.html;
    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 2014-11-03
    • 2020-10-20
    • 2017-10-31
    相关资源
    最近更新 更多