How to disable Nginx server push refreshing webpage (Disable cached resources pushes)?

I have added Nginx http/2 server push to my WordPress site selected files (fonts, CSS and JS). It is working as expected. Although, there is a problem.

If the visitor navigates to another page on my site again Nginx server pushes the same fail even if they are already cached on the visitor's web browser. Each page preview Nginx re-push every server push files.

Is there any way to temporarily disable server push if the files already cached on the visitor device?


Solution 1:

You captured a known issue with HTTP2/Push and one of the reasons its being deprecated - Chrome is evaluating the removal of HTTP2/Push. I'd caution about spending a ton of engineering time debugging it.

https://groups.google.com/a/chromium.org/g/blink-dev/c/K3rYLvmQUBY/m/vOWBKZGoAQAJ

Solution 2:

There is no direct mechanism in nginx to perform push selectively.

One approach would be to push resources only if the client doesn't send a cookie with the request.

This approach can be implemented as follows:

In http level, define a map:

map $http_cookie_preloaded $resources {
    "visited" "";
    default "</style.css>; as=style; rel=preload, </image1.jpg>; as=image; rel=preload";
}

And in server block:

server {
    http2_push_preload on;
    add_header Set-Cookie "preloaded=1";
    add_header Link $resources;
}

This way users will get resources pushed on their first visit. They also get a cookie "preloaded", which then prevents the push on subsequent page loads.

The resources are specified inside the map default mapping.