nginx配置選項try_files詳解


 

一.

try_files是nginx中http_core核心模塊所帶的指令,主要是能替代一些rewrite的指令,提高解析效率。官網的文檔為http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

二.

  1.try_files的語法規則:

    格式1:try_files file ... uri;  格式2:try_files file ... =code;

    可應用的上下文:server,location段

  2.try_files的語法解釋:(先貼出官方的解釋,樓主再解釋下)

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 fileparameter 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. 

  關鍵點1:按指定的file順序查找存在的文件,並使用第一個找到的文件進行請求處理

  關鍵點2:查找路徑是按照給定的root或alias為根路徑來查找的

  關鍵點3:如果給出的file都沒有匹配到,則重新請求最后一個參數給定的uri,就是新的location匹配

  關鍵點4:如果是格式2,如果最后一個參數是 = 404 ,若給出的file都沒有匹配到,則最后返回404的響應碼

 3.舉例說明:

 

location /images/ {
root /opt/html/; try_files $uri $uri/ /images/default.gif;
}
比如 請求 127.0.0.1/images/test.gif 會依次查找 1.文件/opt/html/images/test.gif 2.文件夾 /opt/html/images/test.gif/下的index文件 3. 請求127.0.0.1/images/default.gif

4.其他注意事項
1.try-files 如果不寫上 $uri/,當直接訪問一個目錄路徑時,並不會去匹配目錄下的索引頁 即 訪問127.0.0.1/images/ 不會去訪問 127.0.0.1/images/index.html

 

三.

其他用法:

location / {
    try_files /system/maintenance.html
              $uri $uri/index.html $uri.html
              @mongrel;
}

location @mongrel {
    proxy_pass http://mongrel;
}

 

以上中若未找到給定順序的文件,則將會交給location @mongrel處理(相當於匹配到了@mongrel來匹配)

  

 

 

  

 


免責聲明!

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



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