Skip to content

Instantly share code, notes, and snippets.

@anthonyeden
Created March 31, 2018 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonyeden/89186892726802121b9fe7c35b2d6c71 to your computer and use it in GitHub Desktop.
Save anthonyeden/89186892726802121b9fe7c35b2d6c71 to your computer and use it in GitHub Desktop.
Wordpress Caching with Nginx FastCGI

These instructions allow you to setup basic Nginx FastCGI caching for Wordpress. It ensures all admin users, and non-GET requests, bypass the cache.

Create directories with the following commands:

mkdir -p /var/cache/nginxfastcgi
chown www-data: /var/cache/nginxfastcgi

Add the following to the main server blockin your site's .conf file:

fastcgi_cache_key $scheme$request_method$host$request_uri;
fastcgi_cache_lock on;
fastcgi_cache_use_stale error timeout invalid_header updating http_500;
fastcgi_cache_valid 1m;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

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;
}
# Query parameters always go to PHP
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;
}

Add the following to the FastCGI block in your site's .conf file:

        add_header X-Cache $upstream_cache_status;
        fastcgi_cache Wordpress;
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;

Added the following to the HTTP Block in your main nginx.conf file:

fastcgi_cache_path /var/cache/nginxfastcgi levels=1:2 keys_zone=Wordpress:1m inactive=1m max_size=64m;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment