Nginx配置需求:React单页应用根据Query参数返回指定JS或默认文件
解决方案
场景1:不存在时返回/runtimes/default.js
修改Nginx配置,通过try_files在请求处理环节直接完成文件存在性检查与降级处理:
server{ server_name testing001.example.com; # 优先匹配theRuntime.js请求 location ~* ^/theRuntime\.js { root /var/www/testing001; # 初始化目标文件为default.js,兼容id为空的情况 set $target_file "/runtimes/default.js"; # 若id参数存在,替换为对应文件路径 if ($arg_id != "") { set $target_file "/runtimes/$arg_id.js"; } # 尝试加载目标文件,不存在则直接返回default.js try_files $target_file /runtimes/default.js; } location / { root /var/www/testing001; try_files $uri /index.html; } }
场景2:不存在时返回自定义字符串
如果不需要返回文件,而是直接返回一段通用JS代码,可使用如下配置:
server{ server_name testing001.example.com; location ~* ^/theRuntime\.js { root /var/www/testing001; set $target_file "/runtimes/$arg_id.js"; # id为空时默认指向default.js if ($arg_id = "") { set $target_file "/runtimes/default.js"; } # 检查目标文件是否存在,不存在则返回自定义字符串 if (!-f $document_root$target_file) { add_header Content-Type application/javascript; return 200 "// Default runtime\nconsole.log('Loaded default runtime logic');"; } # 文件存在则正常返回 try_files $target_file =404; } location / { root /var/www/testing001; try_files $uri /index.html; } }
原配置问题说明
你之前的配置通过rewrite跳转后,若目标文件不存在,Nginx会继续匹配后续的location /规则,最终返回React的index.html;若没有匹配到合适规则则返回404。上述方案通过在专属location内完成文件检查与降级,避免请求流入单页应用的路由规则。
内容的提问来源于stack exchange,提问作者Pastilhas
相关产品推荐
相关产品推荐

