/ nginx / docs


PHP caching / NOT REVERSE PROXY CACHING

This document is about caching content on each machine not the proxy they are connected to.

What is a reverse proxy?

Difference between reverse proxy caching and PHP caching

Reverse proxy cache

PHP caching

Setup the cache

In this tutorial we will set 2 caches:

Define those caches in the nginx.conf

Explanation

Tell NGINX that we want to control cache by our own

By default NGINX cache reacts to Cache headers

Define allowed request methods that can be cached

In case if we don’t want to cache PUT (update) requests or others.

Use the 1 hour unauth cache for a static content like text

See a working example.

Parameters

location /static-text {
	try_files $uri /index_cached_1h.php?$args;
}
location ~ \index_cached_1h.php$ {
	internal;
	fastcgi_cache_key "$scheme$request_method$host$request_uri$http_language";
	fastcgi_cache cache_1h;
	fastcgi_cache_valid 1h;
	add_header Cache-Status "$upstream_cache_status, 1h" always;
	include snippets/fastcgi-php.conf;
}

In this example cache’s file name fastcgi_cache_key is based on:

So if any of these values changes then a new cache is written.

Done

Test

Use the 5 minute auth cache for a user dependant content that can be 5 minutes old

Like FAQ that depends on the user that has been logged in. Like there could be different questions for a business and a personal account.

Parameters

The main differences from the example above:

The authorization is provided with one extra header cid ($http_cid) which is a unique ID that works the same as a session id or a JWT token. This header must be sent with the request manually just like the ‘Language’ header ($http_language).

Here’s an example how to do that:

setcookie('cid', hash('sha256',mt_rand()),time()+60*60*24*7, '/', $_SERVER['HTTP_HOST'], false, false);

Hints:

This header is used at the end of the fastcgi_cache_key with the $http_cid variable where the pattern is $http_HEADER_KEY.

location /faq {
	try_files $uri /index_cached_5m_auth.php?$args;
}
location ~ \index_cached_5m_auth.php$ {
	internal;
	fastcgi_cache_key "$scheme$request_method$host$request_uri$http_language$http_cid";
	fastcgi_cache cache_5m_auth;
	fastcgi_cache_valid 5m;
	add_header Cache-Status "$upstream_cache_status, 5m_auth" always;
	include snippets/fastcgi-php.conf;
}

Test

Additional note

If you don’t want the cache to be used if the authorization ID cid have not been sent then you just need to add a condition that changes blocks according to the $http_cid value.

Example

location /faq {
	set $index_file 'index.php';
	if ($is_auth = true) {
		set $index_file 'index_cached_5m_auth.php';
	}
	try_files $uri /$index_file?$args;
}

Resources