Sample Nginx FastCGI Cache Configuration File

Posted on October 6, 2016 at 8:57 pm

Example Nginx FastCGI cache configuration file for a vhost:

#FASTCGI MICROCACHE - START#
fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=microcache:100m max_size=1024m inactive=1h;
add_header X-Cache $upstream_cache_status;
#FASTCGI MICROCACHE - END#
 
server {
        listen 80;
        server_name website.com;
 
        [...]
 
        #FASTCGI MICROCACHE - START#
 
        set $no_cache 0;
 
        # POST requests and urls with a query string should always go to PHP
        if ($request_method = POST) {
            set $no_cache 1;
        }
        if ($query_string != "") {
            set $no_cache 1;
        }
 
        # Don't cache uris containing the following segments
        if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php
                    |wp-.*.php|/feed/|index.php|wp-comments-popup.php
                    |wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml
                    |[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
 
            set $no_cache 1;
        }
 
        # Don't use the cache for logged-in users or recent commenters
        if ($http_cookie ~* "PHPSESSID|comment_author|wordpress_[a-f0-9]+
                    |wp-postpass|wordpress_logged_in") {
            set $no_cache 1;
        }
 
        #FASTCGI MICROCACHE - END#
 
        [...]
 
        location / {
            try_files $uri $uri/ /index.php?$args;
        }
 
        [...]
 
	# Handle .php files
        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
 
	    #FASTCGI MICROCACHE - START#
            fastcgi_cache_key $scheme$host$request_uri$request_method;
            fastcgi_cache microcache;
            fastcgi_cache_valid 200 301 302 30s;
            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;
            fastcgi_cache_bypass $no_cache;
            fastcgi_no_cache $no_cache;
	    #FASTCGI MICROCACHE - END#
 
            [...]
        }
 
        [...]
}

References:

Module ngx_http_fastcgi_module

Receive updates via email

Other Posts

Updated Posts