Following line does't have /products.*
page. This tells Nginx to cache all product pages by default.
Idea is fast loading product pages will improve scalability of a store and also conversion.
# Don't cache uris containing the following segments
if ($request_uri ~* "(/shop.*|/cart.*|/my-account.*|/checkout.*|/addons.*|/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
set $skip_cache 1;
}
WooCommerce uses a cookie woocommerce_items_in_cart
to track if something is added to cart. It is 0 (zero) by default.
The value changes to "1" (one) as soon as a visitor add first product to cart.
The value stays "1" even if a user adds more items to cart. The cookie is used as binary flag.
if ( $cookie_woocommerce_items_in_cart = "1" ){
set $skip_cache 1;
}
Above code snippet starts skipping cache as soon as first item is added to the cart.
WooCommerce sets a session cookie for every new visitor by default.
If a cookie header get's cached in Nginx's fastcgi-cache, that cookie will be delivered to all visitors creating "session-conflict" or "cart-conflict".
In simple words, it he do not take care of cookies, items added by one visitor might appear in another visitors cart.
So we need to prevent cookies for "window shoppers".
more_clear_headers
is a NGINX module which clears Set-Cookie
header from upstream PHP/WordPress' HTTP response.
if ($skip_cache = 0 ) {
more_clear_headers "Set-Cookie*";
set $rt_session "";
}
The third line in above code block has a variable $rt_session
.
This is a custom NGINX variable which will have null (same) value when cached pages are supposed to be served.
The same value is acceptable because all cached pages will look same. The custom variable is used inside NGINX fastcgi-cache key on line:
fastcgi_cache_key "$scheme$request_method$host$request_uri$rt_session";
The custom variable $rt_session
is used further to set to a unique value for each shopping session.
This is needed because different users might have different cart content. So they must not see each other's cache.
This is done by following lines:
if ($http_cookie ~* "wp_woocommerce_session_[^=]*=([^%]+)%7C") {
set $rt_session wp_woocommerce_session_$1;
}
Above basically set $rt_session
to wp_woocommerce_session_
id.
This variable is set on each request, but line set $rt_session "";
in previous step ensures we do not have unique cache key for "window shoppers". This avoids cache fragmentation.
- This technique might break some WooCommerce addons which depends on wp_woocommerce_session from beginning. In reality I haven't seen a single addon breaking. But I hardly tested a dozen WooCommerce addons.
- Simplify.
- Test it with redis full-page cache.