Nginx 指令详解
try_files
语法:try_files file … uri;或 try_files file … = code;
默认值:无
作用域:server location
语法解释:
官方:Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the *file*parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the *uri* specified in the last parameter is made.
翻译:
首先:按照指定的顺序检查文件是否存在,并使用第一个找到的文件进行请求处理
其次:处理是在当前上下文中执行的。根据 root 和 alias 指令从 file 参数构造文件路径。
然后:可以通过在名称末尾指定一个斜杠来检查目录的存在,例如“ $uri/”。
最后:如果没有找到任何文件,则进行内部重定向到最后一个参数中指定的 uri。
自己理解的:按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示文件夹),如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。
注:只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部的 URL 的指向。最后一个参数是回退 URL 且必须存在,否则会出现内部 500 错误。命名的 location 也可以使用在最后一个参数中。
举例说明
示例一:
location / {
root data;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
解释配置:
root:设置静态根目录为 data
index:设置目录的默认文件为 index.html 、index.htm
try_files:设置文件查找规则为 $uri $uri/ /index.html。即3个规则,先从 $uri 查找,再从 $uri/ 目录中查找,最后查找 /index.html。
例子:根据上面的配置,当请求 http://localhost:3004/api 时,$uri 为 /api。当前try_file 具体为:/api、/api/、/index.html,其中 / 表示根目录(根据 root 或 alias 来指定)。
查找逻辑:
首先:检查 data 目录中是否存在 api 文件,如果存在,则返回文件;如果不存在,则进行下一步。
其次:检查 data 目录中是否存在 api/ 目录,如果存在,则在检查 api/ 目录中是否存在 index.html 或者 index.htm 文件(由 index 指定);如果存在,则返回该文件。如果不存在,则进行下一步。
最后:检查 data 目录中是否存在 index.html 文件。如果存在,则返回文件;如果不存在,则返回 404。
示例二:
location /pngs/ {
root /data/user/;
index index.html index.htm;
try_files $uri $uri/ /pngs/file.png;
}
根据上面的配置,当请求 http://localhost:3003/pngs/rule.png 时, $uri 为 /pngs/rule.png,当前 try_file 查找顺序为,首先是:/data/user/pngs/rule.png,其次是:/data/user/pngs/rule.png/ 文件下的 index 所配置的文件,即: index.html、index.htm,最后是: /data/user/pngs/file.png。
作者:Gakki0725
链接:https://www.jianshu.com/p/46eb10532ba3
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
root. VS. alias
影响 $uri 值: root 时 完整 uri alias 时 不包含location 指定的 路径
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端