【问题标题】:Nginx locationsNginx 位置
【发布时间】:2021-10-05 10:18:34
【问题描述】:

我正在使用 React 开发一个多租户应用程序,一些客户希望将 .html 文件上传到项目的根目录以使用谷歌控制台和类似的东西。除了以下代码之外,我不希望所有这些文件都与应用程序代码混合:

location / {
   try_files $ uri /index.html = 404;
}

我想在 NGINX 中添加一个位置块,允许我将任何其他以 / 开头的 .html 文件转移到另一个文件夹,不包括 /static/example.html 之类的情况。

例子:

/               -> React default
/static/*.html  -> React default
/*.html         -> Derive to new folder

我将不胜感激这方面的任何帮助。

我尝试过这样的事情......

location /*.html {
    root /extras_folder;
}
location / {
    root /project_folder;
    try_files $uri /index.html =404;
}

但是不行

【问题讨论】:

  • 每个租户都有自己的(子)域吗?
  • 没错,每个客户端都有自己的子域
  • 请修改您的标题以提出明确、具体的问题。见How to Ask

标签: reactjs nginx nginx-location


【解决方案1】:

这符合您描述的规则:

    location ^~ /index.html {
        root /project_folder;
        try_files $uri /index.html =404;
    }

    location ~ ^/[^/]+\.html {
        root /extras_folder;
        try_files $uri /index.html =404;
    }

    location / {
        root /project_folder;
        try_files $uri /index.html =404;
    }
  • 第二个块是仅在根路径中的 *.html 上的正则表达式匹配
  • 第三块用于所有其他路径
  • 第一个块是覆盖 / 是 /index.html 的边缘情况 - 否则正则表达式规则总是优先于路径位置块

【讨论】:

    【解决方案2】:

    这个怎么样?

    server {
            listen 80;
            root /project_folder;
    
            location / {
                    try_files $uri @extras_folder;
            }
    
            location @extras_folder {
                    root /extras_folder;
                    try_files $uri @index_html;
            }
    
            location @index_html {
                    try_files /index.html =404;
            }
    }
    

    这首先在/project_folder 中查找,然后在/extras_folder 中查找,如果仍然没有找到文件,则最终服务/project_folder/index.html(如果该文件不存在,则为404)。 在这种情况下,您会将上传的文件放入/extras_folder

    【讨论】:

    • 如果我没记错的话,这意味着“new_folder”将在同一个根目录中,即同一个项目代码,仅在一个文件夹中。理想的情况是一个新的位置块,其根指向另一个文件夹。
    • 是的,你是对的。我更新了答案以启用完全不同的root
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2017-06-09
    • 2018-09-26
    • 2011-07-11
    • 2012-11-09
    • 2018-02-01
    • 2012-11-07
    • 2014-01-30
    相关资源
    最近更新 更多