I have nginx caching setup that ignores logged in users, but I have a lot of users in subscriber roles who SHOULD be served a mostly cached site. Is there a way to only ignore caching for SOME roles (like contributor and above) while leaving caching on for subscribers (and potentially other roles at some point)?
1 Answer
Here is what I ended up doing:
// Set disable cache for certain roles
add_action('init', 'add_custom_cookie_admin');
function add_custom_cookie_admin() {
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$thisrole = $current_user->roles[0];
if($thisrole !== 'subscriber') {
setcookie("disable_cache", $current_user->user_login, time()+43200, COOKIEPATH, COOKIE_DOMAIN);
}
}
}
// and then remove the cookie on logout
function clear_custom_cookie_on_logout() {
unset($_COOKIE["disable_cache"]);
setcookie( "disable_cache", '', time() - ( 15 * 60 ) );
}
add_action('wp_logout', 'clear_custom_cookie_on_logout');
And then I added this to my nginx cache:
if ($http_cookie ~* "disable_cache") {
set $skip_cache 1;
}
-
Thanks for sharing this. Does this mean you removed the normal rule for disabling cache for logged in users? e.g.,
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { set $skip_cache 1; }
– omega33Commented Apr 7, 2018 at 7:34 -
yes exactly, because I only wanted it for SOME users (ie subscribers)– StephenCommented Apr 7, 2018 at 17:25
-
Hi this is exactly what I was looking for but how do you serve the cached files for subscribers in the first place using Nginx? I am using WP-Rocket. By default, there are no cached files for logged in users.– JoaMikaCommented Jun 21, 2018 at 13:02
-
right, so in addition I REMOVED a couple of previous nginx cookie rules that were skipping the cache: wc_session_cookie_[^=]*=([^%]+)%7C and wordpress_logged_in but in your scenario you may have others you need to check your nginx config to see what is skipping the cache currently.– StephenCommented Jun 21, 2018 at 13:10