作者:Gakki
try_files
- 語法:
try_files file … uri;
或try_files file … = code;
- 默認(rèn)值:無
- 作用域: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. -
翻譯:
- 首先:按照指定的順序檢查文件是否存在,并使用第一個找到的文件進行請求處理
- 其次:處理是在當(dāng)前上下文中執(zhí)行的香罐。根據(jù) root 和 alias 指令從 file 參數(shù)構(gòu)造文件路徑卧波。
- 然后:可以通過在名稱末尾指定一個斜杠來檢查目錄的存在,例如“ $uri/”庇茫。
- 最后:如果沒有找到任何文件,則進行內(nèi)部重定向到最后一個參數(shù)中指定的 uri螃成。
- 自己理解的:按順序檢查文件是否存在旦签,返回第一個找到的文件或文件夾(結(jié)尾加斜線表示文件夾),如果所有的文件或文件夾都找不到寸宏,會進行一個內(nèi)部重定向到最后一個參數(shù)宁炫。
-
官方: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
注:只有最后一個參數(shù)可以引起一個內(nèi)部重定向,之前的參數(shù)只設(shè)置內(nèi)部的 URL 的指向氮凝。最后一個參數(shù)是回退 URL 且必須存在羔巢,否則會出現(xiàn)內(nèi)部 500 錯誤。命名的 location 也可以使用在最后一個參數(shù)中罩阵。
舉例說明
- 示例一:
location / {
root data;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
-
解釋配置:
-
root:設(shè)置靜態(tài)根目錄為
data
-
index:設(shè)置目錄的默認(rèn)文件為
index.html
竿秆、index.htm
-
try_files:設(shè)置文件查找規(guī)則為
$uri $uri/ /index.html
。即3個規(guī)則稿壁,先從$uri
查找幽钢,再從$uri/
目錄中查找,最后查找/index.html
傅是。
-
root:設(shè)置靜態(tài)根目錄為
例子:根據(jù)上面的配置匪燕,當(dāng)請求 http://localhost:3004/api 時,
$uri
為 /api喧笔。當(dāng)前try_file 具體為:/api
帽驯、/api/
、/index.html
书闸,其中/
表示根目錄(根據(jù) 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;
}
- 根據(jù)上面的配置奢米,當(dāng)請求 http://localhost:3003/pngs/rule.png 時,
$uri
為 /pngs/rule.png涉波,當(dāng)前 try_file 查找順序為苍日,首先是:/data/user/pngs/rule.png,其次是:/data/user/pngs/rule.png/ 文件下的 index 所配置的文件拦耐,即: index.html、index.htm固翰,最后是: /data/user/pngs/file.png。