Hi @davidffff0101 –
You’ve got it right. When WP Super Cache serves a cached page, it does so very early, before WordPress fully loads, so hooks like send_headers never run for that request. That’s why anonymous visitors don’t get your CSP header while logged-in users (who always get uncached pages) do.
WP Super Cache has a setting for this:
- Go to Settings → WP Super Cache → Advanced.
- Under Miscellaneous, enable “Cache HTTP headers with page content.“
- Save, then delete the cache (Contents → Delete Cache) so pages get cached again with the headers.
With this enabled, the plugin saves the response headers when a page is first cached, including those set by your mu-plugin through send_headers, and sends them again each time it serves that cached copy. Content-Security-Policy is already on the list of headers the plugin saves, so you don’t need any extra code. If you ever need to save a header that isn’t on that list, you can add it with the wpsc_known_headers filter.
A couple of things to keep in mind:
- The option is greyed out when the caching mode is set to Expert. In Expert mode, cached files are served directly by the web server without loading PHP, so the header has to be added in your server config instead (for example, with Header set
Content-Security-Policy “…” in .htaccess on Apache, or add_header in your nginx config).
- With this option enabled, cached pages are served through PHP instead of as static files. That’s slightly slower, but still much faster than an uncached page.
Another option is to set the CSP header at the server level (.htaccess, nginx, or your CDN). That way it’s sent on every response no matter how the page is served.
Let us know how it goes!
Thanks, it worked very well. Out of curiosity, would you recommend using the cache in Expert mode instead of PHP mode?
I assume that in Expert mode the plugin simply adds rules to WordPress’s .htaccess file, right?
It’s my first time using page caching, so I’m not sure whether the difference could be significant in terms of response times.
Hi @davidffff0101,
Glad to hear it worked!
Yes, Expert mode is the fastest caching method, but Simple mode is the recommended option in WP Super Cache and is almost as fast, while being easier to configure since it doesn’t require changes to your .htaccess file.
You can read more about the different caching methods and the recommended settings here:
https://jetpack.com/support/wp-super-cache/initial-wp-super-cache-setup-and-configuration/
Since the original issue is resolved, I’ll go ahead and mark this thread as resolved. If anything else comes up, feel free to open a new topic.