NGINX –在单个服务器上服务多个SPA

问题描述 投票:1回答:1

我们有一个开发服务器,其中包含许多单页应用程序,这些应用程序还可以在前端处理路由。

通常对于单页应用程序,我认为您需要配置以下内容:

location /some/path {
  try_files $uri $uri/ /index.html?$args;
}

现在,在我们的开发服务器上,为放置在其中的每个小型测试应用程序重新配置nginx进行了大量工作。

我想:

  • 如果找到,则提供文件
  • 如果路径是文件夹,则提供index.html文件
  • 如果找不到,请返回一个文件夹并尝试查找index.html并将其投放
  • 尝试上一步,直到找到index.html文件
  • 例如,到达定义的根路径时,请停止尝试。 / some / path,如果没有index.html,则返回文件夹内容

如果某种形式的while循环是不可能的(由于它仅用于开发目的,性能不太关键,我可以将其限制为最多6个文件夹。这应该涵盖大多数SPA。

示例:

假设我有一个单页应用程序:

/some/path/my-app

然后去:

/some/path/my-app/page1/subpage2/id3

它应该尝试:

  • / some / path / my-app / page1 / subpage2 / id3(无匹配项)
  • / some / path / my-app / page1 / subpage2 / id3 / index.html(不匹配)
  • / some / path / my-app / page1 / subpage2 / index.html(不匹配)
  • / some / path / my-app / page1 / index.html(不匹配)
  • / some / path / my-app / index.html(MATCH!)

P.S。我主要是前端开发人员,我对nginx的了解非常有限。

nginx nginx-location nginx-config
1个回答
1
投票

您可以使用命名位置作为try_files语句的最后一个参数,以执行内部rewrite爬上目录树。在声明重定向循环之前,Nginx会将其限制为大约10次迭代。

例如:

root /path/to/root;
index index.html;

location / {
    try_files $uri $uri/ @rewrite;
}
location @rewrite {
    rewrite ^/(.+/)?. /$1 last;
}

indextry_files指令处理寻找index.htmlrewrite语句通过删除/之后的一个或多个字符来截断URI。

© www.soinside.com 2019 - 2024. All rights reserved.