Skip to content

Instantly share code, notes, and snippets.

@2shrestha22
Last active February 23, 2023 05:47
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save 2shrestha22/2db4c1e1e898f83b016b2649775430fa to your computer and use it in GitHub Desktop.
Cloudflare workers script to enable edge-cache. Use Official cloudflare wordpress pulgin for auto cache purge management
// Stop CF edge from caching your site when specific wordpress cookies are present
// script found in https://www.mmaton.com/2018/07/02/cloudflare-cache-anonymous-requests/
addEventListener('fetch', event => {
event.respondWith(noCacheOnCookie(event.request))
})
async function noCacheOnCookie(request) {
// Determine which group this request is in.
const cookie = request.headers.get('Cookie')
// Edge Cache for 1 month
const cacheSeconds = 2592000
if (cookie
&& (
cookie.includes(`wordpress_logged`)
|| cookie.includes(`comment_`)
|| cookie.includes(`wordpress_sec`)
|| cookie.includes(`woocommerce_`)
)) {
const bustedRequest = new Request(request, { cf: { cacheTtl: -1 } })
const response = await fetch(bustedRequest)
const newHeaders = new Headers(response.headers)
newHeaders.append('wp-cache-busted', `true`)
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
})
} else {
return fetch(new Request(request, { cf: { cacheTtl: cacheSeconds } }))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment