配置LEMP系统实用教程及技巧示例(1)(6)
如果你有可以缓存的PHP内存,可以使用nginx FastCGI缓存来缓存该内容。在你的nginx.conf中,添加一行,类似这一行:
vi /etc/nginx/nginx.conf
[...]
http {
[...]
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=microcache:10m max_size=1000m inactive=60m;
[...]
}
[...]
缓存目录/var/cache/nginx必须要有,而且对nginx来说必须是可写的:
mkdir /var/cache/nginx
chown www-data:www-data /var/cache/nginx
如果使用tmpfs,你甚至可以把目录直接放入到你服务器的内存中,这在速度上提供了另一个小小的优势——想了解更多的信息,请参阅这篇教程:《使用tmpfs,将文件/目录存储在内存中》(http://www.howtoforge.com/storing-files-directories-in-memory-with-tmpfs)。
在你的vhost配置中,把下列语句块添加到你的location ~ \.php$ {}部分(你可以修改代码段,这取决于内容何时缓存、何时不缓存):
[...]
# 设置var默认值
set $no_cache "";
# 如果没有GET/HEAD,不缓存&通过cookie将用户标记为不可缓存1秒
if ($request_method !~ ^(GET|HEAD)$) {
set $no_cache "1";
}
# 如果需要,不丢弃任何缓存cookie
# (由于某种原因,如果添加到之前的if语句块,add_header失败)
if ($no_cache = "1") {
add_header Set-Cookie "_mcnc=1; Max-Age=2; Path=/";
add_header X-Microcachable "0";
}
# 如果非缓存cookie已被设置,绕过缓存
if ($http_cookie ~* "_mcnc") {
set $no_cache "1";
}
# 如果标记已被设置,绕过缓存
fastcgi_no_cache $no_cache;
fastcgi_cache_bypass $no_cache;
fastcgi_cache microcache;
fastcgi_cache_key $scheme$host$request_uri$request_method;
fastcgi_cache_valid 200 301 302 10m;
fastcgi_cache_use_stale updating error timeout invalid_header http_500;
fastcgi_pass_header Set-Cookie;
fastcgi_pass_header Cookie;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
[...]
所以整个location ~ \.php$ {}部分看起来如下:
[...]
location ~ \.php$ {
# 设置var默认值
set $no_cache "";
#如果没有GET/HEAD,不缓存&通过cookie将用户标记为不可缓存1秒
if ($request_method !~ ^(GET|HEAD)$) {
set $no_cache "1";
}
#如果需要,不丢弃任何缓存cookie
#(由于某种原因,如果添加到之前的if语句块,add_header失败)
if ($no_cache = "1") {
add_header Set-Cookie "_mcnc=1; Max-Age=2; Path=/";
add_header X-Microcachable "0";
}
#如果非缓存cookie已被设置,绕过缓存
if ($http_cookie ~* "_mcnc") {
set $no_cache "1";
}
#如果标记已被设置,绕过缓存
fastcgi_no_cache $no_cache;
fastcgi_cache_bypass $no_cache;
fastcgi_cache microcache;
fastcgi_cache_key $scheme$host$request_uri$request_method;
fastcgi_cache_valid 200 301 302 10m;
fastcgi_cache_use_stale updating error timeout invalid_header http_500;
fastcgi_pass_header Set-Cookie;
fastcgi_pass_header Cookie;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
try_files $uri =404;
include /etc/nginx/fastcgi_params;
fastcgi_pass unix:/var/lib/php5-fpm/web1.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_intercept_errors on;
}
[...]
这将把返回代码是200、301和302的页面缓存10分钟。
评论暂时关闭