Nginx的try_files指令详解

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
根据上面的配置,当请求 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

转自链接:https://www.jianshu.com/p/46eb10532ba3
posted @ 2023-04-08 22:09  北京流浪儿  阅读(664)  评论(0编辑  收藏  举报