WordPress的缓冲插件wp-super-cache默认支持apahce的缓冲方式,在生成了静态页面数据后,通过.htaccess的规则直接让apache读取静态文件,完全不经过PHP,可以很大的提高博客的页面性能。
但是Nginx的改写规则就没这么容易让代码来配置了,虽然wp-super-cache的第二种缓存方式就是为这种使用环境设计,但实际上是用了PHP来提供静态数据了,在使用apache benchmark压力的时候,php-cgi依然占很高的CPU占有率。
通过编写nginx的rewrite规则还是可以让nginx直接读取静态文件,参考来自Code Exchange: nginx rewrite rules for WordPress + WP Super Cache,这里的配置被很多地方引用过,但实际尝试使用过程看到那里面的代码还需要微调。
server { listen 80; server_name blog.ptsang.net; root /var/www/pt-sites/wordpress; index index.html index.htm index.php; location / { # enable search for precompressed files ending in .gz # nginx needs to be complied using –-with-http_gzip_static_module # for this to work, comment out if using nginx from aptitude gzip_static on; # if the requested file exists, return it immediately if (-f $request_filename) { break; } set $supercache_file ''; set $supercache_uri $request_uri; if ($request_method = POST) { set $supercache_uri ''; } # Using pretty permalinks, so bypass the cache for any query string if ($query_string) { set $supercache_uri ''; } if ($http_cookie ~* "comment_author_|wordpress|wp-postpass_" ) { set $supercache_uri ''; } # !!!! IMPORTANT # if we haven't bypassed the cache, specify our supercache file if ($supercache_uri ~ ^(.+)$) { set $supercache_file /wp-content/cache/supercache/$http_host/$1/index.html; } # only rewrite to the supercache file if it actually exists if (-f $document_root$supercache_file) { rewrite ^(.*)$ $supercache_file break; } # all other requests go to Wordpress if (!-e $request_filename) { rewrite ^(.*)$ /index.php?q=$1 last; } } location ~ \.php$ { include fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } } |
需要重点关注的是set $supercache_uri
这一行,这里的路径是wp-super-cache生成静态文件的路径,配置文件起作用的时候,这个路径会和$document_root组成最终静态文件的绝对路径,最终输出文件。所以如果这个路径不对的话,最终还是交给了index.php
,缓冲就不起作用了。
wp-super-cache在wordpress目录/wp-content/cache/supercache/$http_host/
下生成了各个请求url的目录,目录下是一个index.html静态文件,可以在wordpress工作时候,在这个目录下用命令watch find
观察(在缓冲不多的情况下),总之小心的把这个路径写好,因为估计每个博客的permanent link的样式都不一样,wp-super-cache生成的目录也不一样,需要仔细调试一下。
当然这里的规则并没有安全包含了wp-super-cache 插件的功能,比如识别手机客户端之类的,如果需要还得仔细根据插件生成的.htaccess规则来添加到nginx。
完成后用apache benchmark压一下,Request per second应该很容易上百,而且php-cgi应该不会出现在top的列表前面了,CPU应该集中在nginx的子进程上,而且都是个位数CPU占有率,系统的load非常低。
Tips: 发现测试结果不对时,可以尝试删除/wp-content/cache整个目录,让wp重新生成所有缓冲。
顺便说一下,如果仅使用ab测试压力,用不着安装整个apache2,只需要apt-get install apache2-utils
。
发表评论