歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網

nginx try

日期:2017/3/2 9:43:12   编辑:關於Linux

try_files 是nginx0.6.36 後新增一個功能,用於搜索指定目錄下的N個文件,如果找不到fileN,則調用fallback中指定的位置來處理請求。個人認為,作為nginx核心的內容,可以部分替代煩瑣的rewrite功能,筆者把它用在wp super cache的rewrite重寫中,也取得了不錯的效果。

try_files

語法: try_files file1 [file2 ... filen] fallback

默認值: 無

作用域: location

這個指令的作用就是可接收多個路徑作為參數,當前一個路徑的資源無法找到,則自動查找下一個路徑,如當請求的靜態資源不存在,就將請求fallback指定位置到後台服務器上進行動態處理。

簡單的例子:
location / {
try_files index.html index.htm @fallback;
}

location @fallback {
root /var/www/error;
index index.html;
}
筆者的博客剛剛建立起來,wp super cache是不可或缺的一個插件,但默認的supercache是針對apache的.htaccess的,在nginx下的
配置如下:

set $cache /wp-content/cache/supercache/$host;
#wp-super-cache的路徑
listen 80;
server_name _;
location / {
root /home/html/s0001/domains/$host;
index index.php index.html;
#直接調用gzip壓縮後的html靜態文件
add_header Content-Type "text/html; charset=UTF-8";
add_header Content-Encoding "gzip";
try_files $cache/$uri/index.html.gz @proxy;

}
#所有靜態文件都由nginx處理,並用gzip壓縮輸出
location ~* \.(jpg|jpeg|png|gif|css|js|swf|mp3|avi|flv|xml|zip|rar)$ {
expires 30d;
gzip on;
gzip_types text/plain application/x-javascript text/css application/xml;
root /home/html/s0001/domains/$host;
}
#找不到的文件都交給後端的apache處理了
location @proxy {
index index.php index.htm index.html;
root /home/html/$user/domains/$host;
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

這樣一個wordpress博客就配置完成了,是不是很簡單呢^_^~

Copyright © Linux教程網 All Rights Reserved