nginx中的try_files指令解釋


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會觸發一個內部重定向)
轉載:
http://www.2cto.com/os/201210/164157.html
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
在 Nginx 下, 添加以下聲明:

    location / {
       try_files $uri $uri/ /index.php;
    }
https://git.oschina.net/os621/ROCBOSS


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM