Site that allows only logged in customers to visit the Shop page. Keeps redirecting/caching even after they are logged in

Hello!

I have a Wordpress site that allows only logged in customers to visit the Shop page and other Woocommerce pages.

This function is achieved by this PHP code that I added to my child’s theme functions.php.:

add_action( ‘template_redirect’, ‘wc_redirect_non_logged_to_login_access’);
function wc_redirect_non_logged_to_login_access() {

if ( !is_user_logged_in() && ( is_woocommerce() || is_shop() || is_cart() || is_checkout() ) ) {
    wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id')) );
    exit();
}

}

All went well, but after I migrated to WP Engine this function keeps redirecting to a my-account page even after a user is logged in. I contacted WP Engine about cache settings but they said that isn’t the problem.

They added the below listed Woocommerce cache exclusions:

^/cart/     
^/my-account/     
^/checkout/     
^/product-category/     
^/product/     
^/wc-api/     
^/resetpassword/         
product     
wc-api=        
woocommerce_cart_hash     
woocommerce_items_in_cart     
Wp_woocommerce_session_       
wp-resetpass-

But the problem still presists.

They did find that the domain was going through Cloudflare, so I may want to exempt this path from caching. So I made page rule for /my-account/ page - Caching Level - Bypass, but the problem still persists.
Here are my page rules: https://ibb.co/28k84cM

Here is a screenshot of responsive headers info.: https://ibb.co/dMwQ8t5
By, the way when I disable browser cache in browser inspect settings the problem disappears.

Now I have removed the code otherwise users would not be able to access Shop page.

Summary: I have code in functions.php that redirect users to my-account page if they are not logged in and try to visit Shop page or any other Woocommerce page.
When a user is logged in and try to visit Shop page, the browser is still pulling cached redirect without taking into account the added PHP code if rule.
It seems that cache is causing the problem, but I might be wrong.

Another thing that I remember is that before migration, I deleted the Cloudflare Flexible SSL plugin. I thought that maybe that caused the problem, but when I installed it again, the problem still persists.
Also, before migration, I had W3 total cache plugin, I deleted it because it is disallowed for WP Engine.

Any ideas? Thanks!

Best regards,
Rudolfs

Ok, so I managed to solve this problem. I contacted WP Engine and they specifically excluded /shop/ path from caching. This solved the issue.

Take care,
Rudolfs