現在有這樣一個需求,網站根目錄下有靜態檔案,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之後需要再判斷一次檔案存在。