How can I prevent caching of wp_redirect?

I am working on a multisite install where one specific site needs to have access restricted to only users who are logged in AND have a specific user meta set (key=cr_access, val=Yes). If the user is not logged in, or that meta key is not set to Yes, then they should be redirected to the specified url.

The redirect works properly, however it seems to be getting cached. If a user tries to visit a page before logging in, then logs in and tries again, it is still redirecting them to the set url. If I purge the page and object caches, then the user is able to visit the pages. How can I prevent this from getting cached in the first place?

Here is my code:

function hwnycr_redirect(){

//only redirect for blog id 10, non-admin, and exclude home/login pages
if (!is_front_page()  !current_user_can( 'edit_posts' )  get_current_blog_id() == 10  get_the_ID()  13) {

    if(!is_user_logged_in()) {

      wp_redirect('https://example.com');
      exit();

    } else {

      $current_user = wp_get_current_user();
      $cr_access = get_user_meta($current_user-ID, 'cr_access', true);

      if ($cr_access !== Yes) {

        wp_redirect('https://example.com');
        exit();

      }

    }
  }
}

add_action( 'template_redirect', 'hwnycr_redirect',1);

Topic wp-redirect redirect cache Wordpress

Category Web


You should try adding nocache_headers() before you wp_redirect(). It's meant for this exact thing. From the docs:

Set the headers to prevent caching for the different browsers.

Your scenario was mentioned and addressed in a user contributed note in the WP Code Reference. That's where I picked this technique up from.


Been banging my head against the wall on this one for months. The workaround is to set all the of redirected posts under a common slug and have WPEngine force all urls under that slug ( category ) to never cache.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.