Nginx配置文件try_files语法及在WP Super Cache中的应用

try_files 是nginx0.6.36 后新增一个功能,用于搜索指定目录下的N个文件,如果找不到fileN,则调用fallback中指定的位置来处理请求。个人认为,作为nginx核心的内容,可以部分替代烦琐的rewrite功能,笔者把它用在wp super cache的rewrite重写中,也取得了不错的效果。

try_files
语法: try_files file1 [file2 … filen] fallback
默认值: 无
作用域: location

这个指令的作用就是可接收多个路径作为参数,当前一个路径的资源无法找到,则自动查找下一个路径,如当请求的静态资源不存在,就将请求fallback指定位置到后台服务器上进行动态处理。
简单的例子:

1
2
3
4
5
6
7
8
location / {
    try_files index.html index.htm @fallback;
}

location @fallback {
    root /var/www/error;
    index index.html;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
server {
    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;
    }
}