Marketing query strings such as ?utm_source=newsletter&fbclid=IwAR... make your CDN treat every ad or email click as a different URL, so each one misses the cache and lands on your origin server. This guide shows how to strip marketing query strings from the CDN cache key, at the edge or at an Nginx origin. Those visits then come from cache, and your analytics still see the tags.
Quick answer: Remove tracking parameters (utm_*, fbclid, gclid and similar) from the cache key only, and never redirect to strip them. The visitor keeps the full URL, so analytics still work, while all the variants share one cached copy.
- List the query parameters your pages really use (
page,s, filters) so you never strip those. - On Cloudflare, run a Worker that deletes tracking parameters, sorts the rest and uses the result as the cache key.
- On Fastly or Varnish, strip the parameters from
req.urlinvcl_recv. - On an Nginx origin, build
fastcgi_cache_keyfrom the path plus your functional parameters. - Test with two requests that differ only in
fbclid: the second should be a cache HIT.
In this guide
- Before You Start
- How Tracking Query Strings Lower Your Cache Hit Ratio
- Edge Cache Key Normalization vs. URL Rewriting
- Method 1: Normalizing Query Strings with Cloudflare Workers
- Method 2: Stripping Marketing Parameters in Fastly or Varnish VCL
- Method 3: Normalizing at Origin with an Nginx Reverse Proxy
- Check That Tracking Variants Share One Cache Entry
- Don’t Redirect: Keep Client-Side Analytics and Attribution Working
- If It Still Doesn’t Work
- Frequently Asked Questions
- Next Steps

Before You Start
- Access: your CDN account (on Cloudflare, permission to create Workers and routes), or SSH with
sudofor the Varnish and Nginx methods. - A parameter inventory: write down every query parameter that changes a page, such as
page,s, sort and filter options, or cart actions. Stripping one of these serves the wrong cached page to everyone. - Cacheable pages: the origin must send a
Cache-Controlheader that allows shared caching for pages you want cached, and keep personalized pagesprivate. - Time and rollback: about 30 minutes. To undo, remove the Worker route, revert the VCL, or restore your Nginx file and reload after
nginx -tpasses.
How Tracking Query Strings Lower Your Cache Hit Ratio
By default, CDNs like Cloudflare and Fastly include the entire query string in the cache key, the value the CDN uses to decide whether two requests are the same page. (On CloudFront it depends on the cache policy attached to the behavior.)
Take a normal request path:
GET /pricing/ HTTP/2
Host: example.comWhen someone visits without query params, the CDN hashes example.com/pricing/, and serves a clean HIT. But when marketing launches a campaign or sends an email blast, the incoming traffic looks more like this:
GET /pricing/?utm_source=meta&utm_medium=cpc&utm_campaign=spring_sale&fbclid=12345 HTTP/2
GET /pricing/?utm_source=meta&utm_medium=cpc&utm_campaign=spring_sale&fbclid=67890 HTTP/2
GET /pricing/?utm_source=newsletter&mc_cid=a1b2c3 HTTP/2Because values like fbclid, gclid and email campaign IDs are unique per click, the CDN sees each request as a new page. Your origin ends up building the same HTML again for every click. If you’ve already implemented rules like those in our guide on configuring CDN edge cache rules for WordPress dynamic URLs, query string clutter will quietly wipe out those performance gains.
Edge Cache Key Normalization vs. URL Rewriting
There are two main ways to handle this at the edge:
- Cache Key Normalization (Recommended): The CDN strips the tracking parameters only when calculating the internal cache lookup key, but keeps the original query string intact when passing the response to the browser.
- Edge Request Rewriting: The CDN strips the parameters before passing the request downstream or responding to the visitor.
Cache key normalization is almost always what you want. Client-side trackers (Google Tag Manager, GA4, Meta Pixel) rely on reading window.location.search in the browser. Normalizing the key means the visitor gets a cached response from the edge in milliseconds, while their browser still parses the tracking tags in the URL bar.
These common marketing parameters never change server-rendered HTML and should be stripped from your cache key:
utm_source,utm_medium,utm_campaign,utm_term,utm_content(Google Analytics)gclid,gclsrc,wbraid,gbraid(Google Ads)fbclid(Meta / Facebook)msclkid(Microsoft / Bing Ads)ttclid(TikTok Ads)twclid(Twitter / X Ads)mc_cid,mc_eid(Mailchimp)_hsenc,_hsmi(HubSpot)yclid(Yandex)
Method 1: Normalizing Query Strings with Cloudflare Workers
If you’re on Cloudflare, excluding query parameters from the cache key in Cache Rules is an Enterprise-plan setting. On the other plans, a lightweight Worker is the usual way to sanitize the cache key while leaving functional query strings (like ?page=2 or ?s=search) alone.
Create a Worker in your Cloudflare account, paste in the script below, and attach it to a route that covers the pages you want cached (for example example.com/*). It removes the tracking parameters from the cache key and sorts the remaining ones alphabetically:
const TRACKING_PARAMS = new Set([
'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',
'fbclid', 'gclid', 'gclsrc', 'wbraid', 'gbraid', 'msclkid', 'ttclid',
'twclid', 'mc_cid', 'mc_eid', '_hsenc', '_hsmi', 'yclid'
]);
export default {
async fetch(request, env, ctx) {
// Only GET requests are cached
if (request.method !== 'GET') {
return fetch(request);
}
const url = new URL(request.url);
for (const param of Array.from(url.searchParams.keys())) {
if (TRACKING_PARAMS.has(param.toLowerCase())) {
url.searchParams.delete(param);
}
}
// Sort remaining parameters for a consistent cache key
url.searchParams.sort();
const cacheKey = new Request(url.toString(), request);
const cache = caches.default;
// Check CDN edge cache with sanitized key
let response = await cache.match(cacheKey);
if (!response) {
// Fetch from origin if cache miss
response = await fetch(request);
// Only cache successful responses
if (response.status === 200) {
ctx.waitUntil(cache.put(cacheKey, response.clone()));
}
}
return response;
},
};The Workers Cache API only stores cacheable responses: your origin has to send a Cache-Control header that allows shared caching (for example s-maxage=300), and responses with Set-Cookie are never stored. Keep Cache-Control: private on personalized pages so they stay out of this cache.
By sorting whatever parameters remain, requests like /shop/?size=m&color=blue and /shop/?color=blue&size=m both hit the exact same cache entry instead of caching twice.
Method 2: Stripping Marketing Parameters in Fastly or Varnish VCL
If you’re running Fastly or self-hosting Varnish, clean up the query string inside vcl_recv before the hashing step.
On a self-hosted Varnish server, add this to /etc/varnish/default.vcl (on Fastly, add it as custom VCL in your service). It must run before the hashing step:
sub vcl_recv {
# Strip tracking query strings from the URL
if (req.url ~ "(\?|&)(utm_[a-z]+|fbclid|gclid|gclsrc|wbraid|gbraid|msclkid|ttclid|twclid|yclid|mc_[a-z]+|_hs[a-z]+)=") {
# Remove each tracking pair but keep the ? or & in front of it
set req.url = regsuball(req.url, "(\?|&)(utm_[a-z]+|fbclid|gclid|gclsrc|wbraid|gbraid|msclkid|ttclid|twclid|yclid|mc_[a-z]+|_hs[a-z]+)=[^&]*", "\1");
# Collapse the separators left behind
set req.url = regsuball(req.url, "&&+", "&");
set req.url = regsub(req.url, "\?&", "?");
set req.url = regsub(req.url, "[?&]$", "");
}
}Varnish strips the listed parameters out of req.url before vcl_hash runs, so every visitor with ad tracking tags hits the same cached object. Note that your backend no longer receives those parameters either.
On self-hosted Varnish, check that the file compiles with sudo varnishd -C -f /etc/varnish/default.vcl > /dev/null before reloading. No output means it compiled; an error names the line to fix.
Method 3: Normalizing at Origin with an Nginx Reverse Proxy
If your CDN forwards full query strings straight through to your origin, you can handle the cleanup in Nginx’s own page cache. Pair this with immutable cache-control headers behind a CDN for your static assets.
A map regex only removes one match per evaluation, so it cannot strip an arbitrary number of tracking parameters. Do the reverse instead: build the cache key from the path plus the parameters that actually change the page. Add this inside the http block of /etc/nginx/nginx.conf:
# Cache zone for rendered pages
fastcgi_cache_path /var/cache/nginx/pages levels=1:2 keys_zone=pages:50m inactive=60m;
# The requested path without its query string
map $request_uri $request_path {
"~^(?<path>[^?]*)" $path;
}Then use $request_path and an explicit list of functional parameters as the cache key in your server block:
server {
listen 80;
server_name example.com;
root /var/www/example.com/public;
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000;
fastcgi_cache pages;
fastcgi_cache_valid 200 10m;
# Only "page" and "s" are part of the key; utm_*, fbclid, gclid and the rest are ignored
fastcgi_cache_key "$scheme$request_method$host$request_path|page=$arg_page|s=$arg_s";
}
}List every parameter your pages really vary on; a forgotten one means visitors get the wrong cached page. On a site with logins, add fastcgi_cache_bypass and fastcgi_no_cache rules for session cookies first.
Check the config syntax and reload Nginx. The && means the reload only runs if the test passes, so a typo cannot take the site down:
sudo nginx -t && sudo systemctl reload nginxYou should see syntax is ok and test is successful before the reload.
Check That Tracking Variants Share One Cache Entry
Once your edge rules are live, test them with two requests that differ only in their tracking values.
Run these from your own computer’s terminal:
# First request with user A's Facebook click ID
curl -I -s "https://example.com/pricing/?utm_source=facebook&fbclid=IwAR111111111" | grep -iE '(x-cache|cf-cache-status|age)'
# Second request with user B's Facebook click ID
curl -I -s "https://example.com/pricing/?utm_source=facebook&fbclid=IwAR222222222" | grep -iE '(x-cache|cf-cache-status|age)'The header names depend on your setup: cf-cache-status on Cloudflare, x-cache on Fastly and many Varnish setups. The first request warms up the cache and may return a miss:
cf-cache-status: MISS
age: 0The second request has a different fbclid, but it should be a cache hit. The age value (seconds since the copy was stored) will differ for you:
cf-cache-status: HIT
age: 14The second visitor is served from the edge; the request never reaches your backend. If both requests show a miss, see the troubleshooting list below.
Don’t Redirect: Keep Client-Side Analytics and Attribution Working
The biggest trap is trying to clean URLs by throwing a 301 redirect at incoming traffic.
If someone clicks an ad for example.com/?utm_source=newsletter and your server immediately returns a 301 Moved Permanently to example.com/, the browser drops the query parameters on the spot. By the time your Google Analytics script loads on the target page, window.location.search is empty. Your paid campaign traffic gets dumped into the “Direct” bucket.
Here is how to keep your data accurate:
- Never issue a 301 or 302 edge redirect to strip tracking parameters.
- Normalize the cache key only at your CDN tier. The user’s browser still needs the full query string in the address bar on initial load.
- If you want clean URLs in the browser bar for visual aesthetics, clean them client-side after your analytics tags fire using the MDN History API documentation:
// Clean up tracking query params in the browser without reloading or breaking GA4
window.addEventListener('load', () => {
const url = new URL(window.location.href);
const cleanParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid'];
let cleaned = false;
cleanParams.forEach(param => {
if (url.searchParams.has(param)) {
url.searchParams.delete(param);
cleaned = true;
}
});
if (cleaned) {
window.history.replaceState({}, document.title, url.pathname + url.search + url.hash);
}
});This removes the clutter from the address bar without causing a page refresh. Attribution only survives if your analytics tags have read the URL before the load event fires, so check your campaign reports after adding it.
If It Still Doesn’t Work
- Both requests are a MISS: the origin probably sends
Cache-Control: private,no-storeor aSet-Cookieheader, so nothing is stored. Check the origin’s headers withcurl -Iand allow shared caching for that page. - The Worker never seems to run: its route does not match the hostname or path, or the hostname is not proxied through Cloudflare. Workers only run on traffic that passes through Cloudflare.
- Visitors see the wrong page (page 2 shows page 1): a parameter that changes the page was stripped, or left out of the Nginx cache key. Add it back and purge the cache.
- Campaign traffic shows up as “Direct”: something is redirecting to strip the parameters. Remove the redirect and normalize the cache key only.
Frequently Asked Questions
Does stripping query strings at the edge break Google Ads conversion tracking?
No, as long as you do not redirect with a 301/302. Normalizing the cache key serves the cached HTML payload while keeping the original ?gclid=... URL intact in the browser address bar. Client-side tracking scripts read the parameter directly from window.location after the page loads.
What happens to search and filter queries on ecommerce sites?
Functional params like ?page=2, ?filter_color=black, or ?s=keyword must stay in the cache key. The Cloudflare Worker and VCL examples only strip an explicit list of known marketing parameters, and the Nginx example names the functional parameters in its cache key, so application-level filters still generate separate, correct cache entries.
Does Cloudflare ignore UTM parameters by default?
No. By default Cloudflare includes the full query string in the cache key, so ?utm_source=a and ?utm_source=b are cached as separate copies. Excluding specific parameters in Cache Rules is an Enterprise setting; on other plans, a Worker like the one above does the same job.
Should I strip tracking query parameters inside WordPress via PHP?
No. Once a request hits PHP, your web server has already spun up workers and burned CPU cycles booting the app. Edge normalization handles this before traffic ever reaches your infrastructure, keeping server load flat.
Next Steps
Watch your CDN’s cache hit ratio for a few days after the change, and check one campaign report to confirm attribution still works. Then make sure logged-in users and shopping carts bypass the cache, as described in our guide to configuring CDN edge cache rules for dynamic URLs and cookies.
Even with clean cache keys, a big email blast can send many requests at the moment a cached page expires. To keep those from piling onto your origin, see how to prevent CDN cache stampedes with origin shield and request collapsing.

