nginx try_files指令判斷檔案是否存在執行個體_nginx

來源:互聯網
上載者:User

現在有這樣一個需求,網站根目錄下有靜態檔案,static目錄下也有靜態檔案,static目錄下的靜態檔案是程式批量產生的,我想讓nginx在地址不變的前提下優先使用static目錄裡面的檔案,如果不存在再使用根目錄下的靜態檔案,比如訪問首頁http://example.com/index.html則nginx返回/static/index.html,如果不存在返回/index.html。

經過一番研究可以用if指令實現,關鍵配置如下,這條配置需要放到靠前的位置

複製代碼 代碼如下:

if (-e $document_root/static$request_uri) {
 rewrite ^/(.*)$ /static/$1 break;
 break;
}

這裡有兩點需要注意:

nginx變數預設應該開頭有反斜線而結尾沒有。

nginx字串和變數可以直接連接,如果可能有歧義可以花括弧括起變數名稱,整個字串必須加雙引號

複製代碼 代碼如下:
"${document_root}/static${request_uri}"

是用這種方式有一個缺點,index指令指定的檔案不會起作用,比如訪問http://example.com/就會404,必須顯示的指定檔案名稱才行http://example.com/index.html。可以用rewrite修複,但是感覺不爽,在nginx陷阱頁面突然發現一個針對性的指令try_files

複製代碼 代碼如下:

set $static "/static";
try_files $static$uri $static$uri/index.html /index.php;

參考頁面

http://wiki.nginx.org/Pitfalls

後來發現$uri變數本身會自動添加index.html尾碼,經過實驗這樣寫也是可以的

複製代碼 代碼如下:

if (-e "${document_root}/static${uri}") {
 rewrite ^/(.*)$ /static/$uri break;
}

if (-e $request_filename) {
 break;
}


因為最後不存在的檔案都寫到index.php去了所以上面rewrite之後需要再判斷一次檔案存在。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.