使用查询字符串中的自定义文件进行响应,如果文件不存在则使用默认文件

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

我有一个 nginx 服务器,运行一个 React 单页应用程序,简单的东西:

server{
    server_name testing001.example.com;

    location / {
      root /var/www/testing001;
      try_files $uri /index.html;
    }
}

在我的

/var/www/testing001
目录中,除了应用程序文件之外,我还有一个目录:

\runtimes
\runtimes\1.js
\runtimes\2.js
\runtimes\3.js
...
\runtimes\default.js

我希望所有请求

https://testing.example.com/theRuntime.js?id={1,2,3,4}

  • 根据 id 查询字符串为我提供相应的文件
    • 这工作正常,使用:
location ~* ^/theRuntime\.js {
        if ($arg_id != "") {
            set $id $arg_id;
            rewrite ^ /runtimes/$id.js last;
        }
    }
  • 如果 /runtimes/$id.js 文件不存在,我想提供 /runtimes/default.js,甚至只是直接来自 nginx 的通用字符串,我不在乎
    • 这是我无法弄清楚的部分,我尝试了很多组合,它要么停止为我提供任何文件(404),要么在某些情况下,它默认为根
      index.html
nginx nginx-config
1个回答
0
投票
server{
    server_name testing001.example.com;
    root /var/www/testing001;

    location / {
        try_files $uri /index.html;
    }
    location = /theRuntime.js {
        try_files /runtimes/$arg_id.js /runtimes/default.js =404;
    }
}

root
移至
server
块中,以便它服务于两个
location
块。

您需要匹配单个 URL,因此使用 “完全匹配”

location
语法。

id
参数可用作
$arg_id

try_files
将按顺序测试
/var/www/testing001
下是否存在多个路径名。

最终的

=404
永远不会到达。参见
try_files

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