Link Search Menu Expand Document
Table of contents

fastCGI Logic - cache php output HTML file

client » nginx (micro cache) «–» php processor

cached after php returns html file

Configuration

fastcgi_cache_path /tmp/nginx_cache levels=1:2 keys_zone=MY_cache:100m inactive=60m use_temp_path=off;

The break down:

fastcgi_cache_path cache name
/tmp/nginx_cache define the path for where to keep the cache
levels=1:2 break cache in levels
keys_zone=[zone-name]:100m define name of the server block
inactive=60m cache TTL
use_temp_path=off disable temp path (without defined cache path can cause unexpected caching behaviour)
fastcgi_cache_key "$scheme$request_method$host$request_uri" 

The break down:

$scheme $request_method $host $request_uri
https:// GET domain.com /blog/article

Example

events {...}

http {
    include mine.type; 

    gzip on;
    gzip_comp_level 3; 
    gzip_types text/css; 
    gzip_types text/javascript;

    fastcgi_cache_path /tmp/nginx_cache levels=1:2 keys_zone=zone_1:100m inactive=60m;
    fastcgi_cache_key "$scheme$request_method$host$request_uri"; 
    #safe option 
    #cache MD5 hashed 

    server {
        listen 80;
        server_name 198.255.25.1;
        root /sites/demo; 
        index index.php index.html;

        #cache by default 
        set $no_cache 0;

        if ($request_method = POST) {
            set $no_cache 1;
        }

        if ($arg_skipcache = 1) {
            set $no_cache 1;
        } #use variable `$arg`, Eg: https://example.com/?skipcache=1

        location / {
            try_files $uri $uri/ =404;
        }

        location ~\.php$ {
            # pass php requests to the php-fpm service (fastcgi)
            include fastcgi.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;

            # Enable cache 
            fastcgi_cache zone_1; 
            # zone_1 is the configured above in the above <keys_zone>
            fastcgi_cache_valid 200 60m;
            # 200 returned file cache for 60 minutes;
            fastcgi_cache_valid 404 10m; 
            # 404 returned file cache for 10 minutes;
            fastcgi_cache_bypass $no_cache;
            # the Variable was set above in HTTP {}
            fastcgi_no_cache $no_cache;
            # if no_cache is 1, no cache 
            add_header php-cache $upstream_cache_status;
        }
    }
}