【问题标题】:NGINX – Serving multiple SPA’s on a single serverNGINX – 在单个服务器上服务多个 SPA
【发布时间】:2020-05-28 15:00:47
【问题描述】:

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

通常对于单页应用程序,我假设您需要配置如下内容:

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(匹配!)

附注我主要是前端开发,我的nginx知识很有限。

【问题讨论】:

    标签: nginx nginx-location nginx-config


    【解决方案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。

    【讨论】:

      猜你喜欢
      • 2018-02-10
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 2014-08-21
      • 2019-06-01
      • 2010-12-05
      相关资源
      最近更新 更多