WordPress如何配置Nginx FastCGI Cache?

缓存优化是WordPress加速中不可缺少的一部分,那么nginx下怎么配置FastCGI Cache?

在nginx config中增加:

fastcgi_cache_path /var/run/nginx-cache levels=1:2       
                   keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
add_header Fastcgi-Cache $upstream_cache_status;

在server中增加:

server {
	# 增加部分 START
	set $skip_cache 0;

	# POST requests and URLs with a query string should always go to PHP
	if ($request_method = POST) {
		set $skip_cache 1;
	}   

	if ($query_string != "") {
		set $skip_cache 1;
	}   

	# Don't cache URIs containing the following segments
	if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php
				 |sitemap(_index)?.xml") {
		set $skip_cache 1;
	}   

	# Don't use the cache for logged-in users or recent commenters
	if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass
		|wordpress_no_cache|wordpress_logged_in") {
		set $skip_cache 1;
	}
	# 增加部分 END

        location ~ \.php$ {
        #        #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
		try_files $uri /index.php;
                include fastcgi_params;
                fastcgi_intercept_errors on;
                fastcgi_pass 127.0.0.1:9000;
                # 增加部分 START
		fastcgi_cache_bypass $skip_cache;
		fastcgi_no_cache $skip_cache;
		fastcgi_cache WORDPRESS;
		fastcgi_cache_valid  60m;
                # 增加部分 END
                #The following parameter can be also included in fastcgi_params file
                fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
       }
}

配置好后需要重启nginx即可。

之后查看网页Response Headers
Fastcgi-Cache: BYPASS 已登录跳过缓存
Fastcgi-Cache: MISS 未命中缓存,可能是并未访问过,没有生成缓存,也有可能其他原因没有命中
Fastcgi-Cache: HIT 未登录,命中缓存

参考文档:
https://www.nginx.com/blog/9-tips-for-improving-wordpress-performance-with-nginx/
https://spinupwp.com/wordpress-static-site-nginx-page-caching/
https://github.com/deliciousbrains/wordpress-nginx

发表回复

您的电子邮箱地址不会被公开。