Using WP_Rewrite instead of _GET parameters to leverage full page caching
Often in code we’re used to doing something like this
http://example.com/my-great-article/?all_pages=1. However, this format doesn’t work well with full page caching provided by our page cache (i.e. Varnish); the query parameters represent different results and need to be treated as such.
Some query parameters that the full page cache is sure are unrelated to the content are automatically ignored by Varnish, such as fbclid, but generally, use of query parameters, such as in the example above, for cacheable responses effectively bypasses page cache and increases the load on the origin servers.
all_pages option here is certainly cacheable. A “print” or “recipe-only” version of a page is another variation we’d want to cache since it won’t change until the underlying article changes.
If the endpoints are not cached, and are used frequently or undergo a spike in activity, then the origin servers will be doing repetitive wasteful work and reducing the resilience of our site.
The most vulnerable endpoints are ones that might suddenly be requested by many users: a json endpoint for a mobile app that has a list of the latest content, or sitemaps or archive pages.
To optimize full page caching, we need to give each separate (cacheable) request its own URL – so we use the
WP_Rewrite API to do so.
You can either use rewrite endpoints or use the add_rewrite_rule() and add_rewrite_tag() functions . You can read more about the Rewrite API here. With the help of these functions, you can rewrite your url so that it will now be:
You can also speed up ajax requests with this technique. You can create
http://example.com/ajax/my_frontend_ajax_function/parameter_1/ to make ajax requests that are cached for 5 minutes for all users with the page cache. This can significantly reduce request time. Note that the ajax rewrites are to index.php and not to admin-ajax.php. You are creating a new endpoint that will call your PHP function, not rewriting the query to pass to admin-ajax.php.
Last updated: April 03, 2023