# Browser and CDN Caching Headers for Visitors

> Sends Cache-Control headers on public pages for logged-out visitors, so a CDN or proxy can cache them for a few minutes.

- Type: PHP
- Runs: Frontend only
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: performance, caching, cdn
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/cache-headers-for-visitors/

## Code

```php
// Seconds browsers (max-age) and shared caches like CDNs (s-maxage) may reuse a page.
$wpide_browser_cache = 300;
$wpide_cdn_cache     = 600;

add_action( 'template_redirect', function () use ( $wpide_browser_cache, $wpide_cdn_cache ) {
    if ( headers_sent() || is_user_logged_in() || is_search() || is_404() || is_preview() || post_password_required() ) {
        return;
    }

    if ( 'GET' !== ( isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : '' ) || ! empty( $_COOKIE['woocommerce_items_in_cart'] ) ) {
        return;
    }

    if ( function_exists( 'is_woocommerce' ) && ( is_cart() || is_checkout() || is_account_page() ) ) {
        return;
    }

    foreach ( array_keys( $_COOKIE ) as $cookie ) {
        if ( 0 === strpos( $cookie, 'comment_author_' ) || 0 === strpos( $cookie, 'wp-postpass_' ) ) {
            return;
        }
    }

    foreach ( headers_list() as $header ) {
        if ( 0 === stripos( $header, 'Cache-Control:' ) ) {
            return; // Something else already decided.
        }
    }

    header( sprintf( 'Cache-Control: public, max-age=%d, s-maxage=%d', $wpide_browser_cache, $wpide_cdn_cache ) );
}, 99 );
```

## Notes

Only useful with a CDN or caching proxy in front of the site, and pages with personal content for visitors must be excluded.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Browser and CDN Caching Headers for Visitors" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
