try_files 指令的官方介紹比較讓人摸不著頭腦,經網上一番總結查看,try_files最核心的功能是可以替代rewrite。 try_files 文法: try_files file ... uri 或 try_files file ... = code 預設值: 無 範圍: server location Checks for the existence of files in order, and returns the first file that is found. A trailing slash indicates a directory - $uri /. In the event that no file is found, an internal redirect to the last parameter is invoked. Do note that only the last parameter causes an internal redirect, former ones just sets the internal URI pointer. The last parameter is the fallback URI and *must* exist, or else an internal error will be raised. Named locations can be used. Unlike with rewrite, $args are not automatically preserved if the fallback is not a named location. If you need args preserved, you must do so explicitly: try_files $uri $uri/ /index.php?q=$uri&$args;按順序檢查檔案是否存在,返回第一個找到的檔案。結尾的斜線表示為檔案夾 -$uri/。如果所有的檔案都找不到,會進行一個內部重新導向到最後一個參數。 務必確認只有最後一個參數可以引起一個內部重新導向,之前的參數只設定內部URI的指向。 最後一個參數是回退URI且必須存在,否則將會出現內部500錯誤。 命名的location也可以使用在最後一個參數中。與rewrite指令不同,如果回退URI不是命名的location那麼$args不會自動保留,如果你想保留$args,必須明確聲明。 try_files $uri $uri/ /index.php?q=$uri&$args; 執行個體分析 try_files 將嘗試你列出的檔案並設定內部檔案指向。 例如: try_files /app/cache/ $uri @fallback; 和 index index.php index.html; 它將檢測$document_root/app/cache/index.php,$document_root/app/cache/index.html 和 $document_root$uri是否存在,如果不存在著內部重新導向到 @fallback 。 你也可以使用一個檔案或者狀態代碼 (=404)作為最後一個參數,如果是最後一個參數是檔案,那麼這個檔案必須存在。 需要明確的是出最後一個參數外 try_files 本身不會因為任何原因產生內部重新導向。 例如nginx不解析PHP檔案,以文本代碼返回 try_files $uri /cache.php @fallback;因為這個指令設定內部檔案指向到 $document_root/cache.php 並返回,但沒有發生內部重新導向,因而沒有進行location段處理而返迴文本 。 (如果加上index指令可以解析PHP是因為index會觸發一個內部重新導向)