首页 文章

HTML5模式下的NGINX,proxy_pass和SPA路由

提问于
浏览
2

我将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,以便它自己处理它们?

1 回答

  • 6

    适合我的解决方案是将指令 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就会从 spa-server 返回/index.html,即SPA . 仍然,URL可用于Angular,路由器将立即在SPA中解析它 .

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

相关问题