Content MarketingData and Development

Replace WordPress Search With Cloudflare Workers and AI Search

Back in May, a bot found the search box on Martech Zone and sent random words to it. Each request made WordPress run three unindexed database scans, and the server fell over. I wrote up the defenses in How to Prevent Resource Exhaustion Attacks on WordPress Search, and then I did the blunt thing: I turned search off.

Today, search is back at martech.zone/s/, and it never runs a query against WordPress or MySQL. The whole feature runs on Cloudflare: a Cloudflare Worker answers each request, a cache absorbs repeats, and an index built by Cloudflare AI Search holds the content. WordPress only prints an empty page that the Worker fills in. This article explains why native WordPress search is a liability, what we built, what it costs, and how to replace your own WordPress search the same way.

Key Takeaways

  • Native WordPress search turns a cheap request into an expensive database scan. A bot only has to send random words to saturate SQL on your server, which is what took Martech Zone down in May 2026.
  • Search is back on Martech Zone, and the rule is that it never touches the WordPress database. A Cloudflare Worker validates the request, a cache answers repeats, and Cloudflare AI Search holds the index. WordPress serves only an empty page shell.
  • Abuse protection lives in the Worker: normalization, one canonical URL per term, rate limiting, a Durable Object that caps cache misses, and a daily query budget. I did not change any Cloudflare WAF, challenge, or Bot Management rule, and I do not use Turnstile on search.
  • Freshness comes from the AI Search crawler, which syncs every 24 hours. No WordPress hook pushes a new post into the index, so a new post is not searchable until the next sync.
  • AI Search billing starts December 1, 2026, with included monthly usage. Only cache misses spend a query, but I have not measured the real bill yet, and this article does not guess at one.
  • You can copy the design: turn on Search for Agents, deploy a Worker on a /s/* route, redirect /?s= before WordPress runs, swap the search form, switch off native search queries, and add tracking. The steps and code are below.

Why Native WordPress Search Is a Liability

WordPress search is a convenience feature that was designed for a quieter internet. When a visitor searches, PHP boots WordPress, builds a query, and asks SQL to find posts whose title, excerpt, or content contain the term. The core of that query looks like this:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE ((wp_posts.post_title LIKE '%term%')
    OR (wp_posts.post_excerpt LIKE '%term%')
    OR (wp_posts.post_content LIKE '%term%'))
  AND wp_posts.post_type IN ('post', 'page')
  AND wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_title LIKE '%term%' DESC
LIMIT 0, 10;

The leading percent sign is the problem. A database index works like the index of a book, sorted from the first letter. A pattern that starts with a wildcard cannot use it, so the database reads every row and compares every word. One search is a small cost. A burst of them is an outage.

Three things make this worse than a normal slow page. The request is cheap to send: a bot needs only a URL and a random word. The result is almost never cached, because every term is different, so a page cache and a CDN cannot help. And the cost lands on the one component you cannot easily scale, the database server. That asymmetry is why search is such a popular target for application-layer denial of service attacks. Automated traffic is also no longer a fringe problem:

Automated traffic accounted for more than 53% of all web traffic in 2025, up from 51% in 2024, and bad bots alone made up 40% of traffic. AI-enabled bot attacks grew 12.5 times, and 27% of bot attacks targeted APIs.

Imperva, a Thales company, 2026 Bad Bot Report

If you have never looked, check your access log for requests that contain ?s=. On many sites, the share of search requests that come from bots is far larger than the share that come from people. I covered how to identify those visitors in Good Bots, Bad Bots, and AI Agents.

What Happened on Martech Zone and Why I Turned Search Off

The May incident was the textbook version of that attack. The traffic was a bot requesting /?s= with random words, and the site’s own write-up recorded what it did to the server:

Back in May, a bot sent random words to the WordPress search endpoint. Each request ran three unindexed LIKE scans on the posts table. The server reached a sustained load average of about 100, MySQL used about 425% of a CPU, and there were around 100 concurrent search queries.

Martech Zone internal incident write-up, May 2026

I tried the usual defenses first. They are in the earlier article: limit the length of a search term, truncate the number of keywords, strip stop words, and refuse the leading wildcard. They help, but they only make each bad request cheaper. They do not stop the request from reaching your database. The site recovered only after I disabled front-end search entirely, which I described in the search section of Taming WordPress. A second fix mattered just as much: I locked the origin server’s web ports to Cloudflare address ranges, because part of the attack had been aimed at an origin IP address that had leaked at some point in the past and never passed through Cloudflare at all.

Turning search off was the right emergency move and the wrong permanent one. In the meantime, the Ask Martech chatbot covered some of the gap, but a chatbot is not a search box. People who search know what they want, and the data is hard to ignore, even though it comes from retail:

Searchers made up 24% of ecommerce visitors but drove 44% of total site revenue, and they converted at 2.5 times the rate of non-searchers. The analysis covered 609 million searches across 113 retail sites between October and December 2024.

Constructor, Beyond Relevance: The Data-Backed Case for Attractiveness as the New Standard for Ecommerce Search Performance, March 2025

Martech Zone is not a store, but the behavior is the same: a visitor who types a query has told you exactly what they need. I wanted the box back, with one rule that I would not bend:

Site search must never hit the WordPress database. No search path may run a WordPress query, a direct database call, or any post lookup to enrich a result. That covers the search page, the old /?s= URL, anonymous REST and AJAX search, and the tools I expose to AI agents.

If search cannot reach the database, a bot cannot take the database down by searching. Everything else follows from that rule.

What We Built on Cloudflare Workers

Cloudflare Workers is a serverless platform that runs your code on Cloudflare’s network, in the data center closest to the visitor. A Worker can sit in front of your website on a route, such as martech.zone/s/*. Any request to a path that starts with /s/ goes to the Worker first, and your server never sees it unless the Worker decides to pass it along. That is the key idea. The Worker intercepts search before WordPress boots, and it can use other Cloudflare services as bindings, which are objects Cloudflare hands your code with no credentials to manage.

For search, I put every resource on Cloudflare. WordPress contributes only a plain page with a form and an empty box for results. Here is each piece and its job:

PieceWhere it livesJob
Search WorkerCloudflare Workers, on the /s/* routeValidates the term, enforces limits, reads the cache, queries the index, and renders results.
Search indexCloudflare AI Search, created by Search for AgentsCrawls the site, converts pages to Markdown chunks, and answers hybrid keyword and vector queries.
Per-location result cacheWorkers Cache APIServes a repeated term from the data center that already answered it.
Global result cacheWorkers KVShares cached results across all locations, and holds an approximate daily query counter.
Query gateDurable Objects (SQLite class QueryGate)Counts uncached queries exactly, per IP address and for the whole site, in one-minute windows.
Loose rate limitsWorkers Rate Limiting bindingsA cheap first fence per IP address. These counts are approximate and local to each location.
Search page shellWordPress themeA term-free page with the header, footer, form, and an empty results slot.
Redirect for /?s=nginx on the originSends old search URLs to the new path without starting PHP.

There is no database binding on this Worker. No D1, no R2, and no Vectorize binding appear in its configuration. The index lives inside AI Search, and Cloudflare notes that the storage, vector indexing, and website crawling it needs run on your account’s behalf and are billed as AI Search, not as separate products.

Diagram of the search request flow: visitor, nginx redirect, Cloudflare Worker, cache check, cache miss gates, AI Search index, and rendered results

How the Search Index Is Built and Kept Fresh

The index is a Cloudflare AI Search instance. Cloudflare calls the one-click version Search for Agents: you switch it on for a domain, and Cloudflare creates an instance named search-for-agents-<zone id>, crawls the site, and exposes a discovery endpoint at /.well-known/search for AI agents. The announcement post explains the idea for agents. For this project I use only the part that matters to a WordPress site, which is the index.

The crawler uses discover mode, which follows your sitemaps and links, converts each page to Markdown, splits it into chunks, and indexes those chunks for hybrid search. Hybrid search combines classic keyword matching with vector similarity, so a query for an acronym and a query for a concept both work. In the instance settings I made four choices:

  • Include only the site itself, and exclude admin, wp-json, wp-content, feeds, tag and author archives, and the search path.
  • Set a content selector so the crawler indexes the article body and not menus and sidebars.
  • Keep four custom metadata fields, taken from tags that Rank Math already prints: the title, the description, the og:image URL, and the published time. The Worker uses them for the result title, snippet, and thumbnail, so it never has to ask WordPress about a post.
  • Leave the public AI Search API and its MCP endpoint off. The Worker binding is the only client.
Diagram of how the AI Search index is built: pages, a 24 hour crawl, Markdown chunks, and a Worker binding

This is the part I want to be precise about. No WordPress hook, cron job, or sitemap ping pushes content into the index. I did not build a sync. Freshness depends entirely on the AI Search crawler, which is set to sync every 24 hours. If you publish a post this morning, expect it to appear in search after the next sync. Nothing here is instant, and I do not claim that it is.

On launch day, the first crawl was still running, so early results came from whatever the crawler had ingested so far. The /.well-known/search endpoint answered with a “Search is being configured” message until the crawl finished. Plan for that if you try this on a large site.

If the crawler ever reports 403 errors in its job logs, your firewall is blocking it. Cloudflare documents a skip rule for that case in its website data source guide. I did not need it: no Cloudflare WAF, challenge, or Bot Management rule was changed for this project.

How a Search Request Is Served

Here is the path of a request, from the first click to the rendered page:

  1. Redirect old URLs. A request for /?s=Network+Storage reaches the origin, where an nginx rule answers with a 301 redirect to /s/Network+Storage/. PHP never starts.
  2. Normalize the term. The Worker Unicode-normalizes it, lowercases it, and requires between 2 and 100 characters and no more than 12 words. Anything that looks like a URL, markup, SQL, a long random token, or a long run of one character gets a 404. No index call, no origin call.
  3. Force one canonical URL. Every term has exactly one address: words joined with plus signs, lowercase, no query string. Other casings or extra parameters get a 301 to that address. This stops cache-busting, where a bot adds a random parameter to defeat the cache.
  4. Check the cheap limit. A loose per-IP Rate Limiting binding runs on every request, cached or not.
  5. Look in the cache. The Worker checks the Cache API in the current location, then KV across the network. A hit returns immediately and spends nothing.
  6. On a miss, pass every gate. The Worker checks the loose per-IP query limit, then the Durable Object gate, then the daily budget. Only then does it query the index, with a five second timeout.
  7. Collapse chunks into pages. The index returns chunks, and several can belong to one page. The Worker keeps the best chunk per URL, drops excluded paths and off-site results, ignores weak vector-only matches, and returns at most 15 results.
  8. Store and render. The Worker caches the result list, fetches the cached, term-free /s/ shell from the origin, and injects the results into the empty slot. Thumbnails, titles, and snippets all come from index metadata.

These are the responses you can expect from the outside:

RequestResponse
/?s=Term301 to /s/Term/, from nginx
/s/?q=Term301 to the canonical /s/term/, from the Worker
/s/Term/ or any non-canonical form301 to the canonical address
/s/term/200 with results, or JSON if the request asks for it
/s/The empty shell from WordPress
Junk input404, no index call
Too many searches429 with a Retry-After header
Index timeout or daily budget reached503

How the Abuse Protection Works

Search that costs money per query needs fences, and I did not want one fence to carry the whole load. The layers are deliberately overlapping:

LayerWhat it stopsNotes
Normalization and junk 404sGarbage and attack-shaped inputNo index call and no origin call.
Canonical URLsCache-bustingExtra query strings are removed by redirect.
Per-IP request limitFloods of any request, cached or notSet to 30 requests per minute per IP address. Approximate.
Per-IP query limitFloods of uncached queriesSet to 8 per minute per IP address. Approximate.
Durable Object gateUncached queries, exactly8 per IP address and 120 for the whole site, per one-minute window.
Daily budgetA runaway bill3,000 uncached queries per UTC day. Approximate, because KV is eventually consistent.
Index timeoutA hung queryFive seconds, then a 503.
Origin fallbackThe Worker being off or bypassedThe origin returns a static 503 for term pages and never searches content.

You may wonder why I added a Durable Object when Workers Rate Limiting exists. The Rate Limiting binding is fast and cheap, but Cloudflare describes its limits as approximate and applied separately in each location, and it points to Durable Objects for strict limits. A bot spread across data centers slips through. My own go-live test showed it. A Durable Object is a single object with its own storage that all locations talk to, so it can count exactly. I send it only cache misses, so it adds no latency to the common path. If it ever errors, the gate fails open and the other layers still apply.

With only the loose per-IP query limiter in place, a go-live test let 31 distinct uncached queries through in about 15 seconds.

After the Durable Object gate was added, a burst of 14 distinct uncached queries from one connection produced 8 successful responses and 6 rate-limited responses with a retry-after of 60 seconds, while cached results kept returning 200.

Martech Zone search go-live tests, November 26, 2026

Two more notes. First, Turnstile is not used on search. A challenge adds friction for every visitor, and the gates already contain the cost. If your traffic is hostile enough that you want it, Cloudflare Turnstile is the tool. Second, the WordPress theme still carries the lockdown from the incident, so a plugin or theme feature that tries to run a search through MySQL gets an empty result instead.

What Visitors and AI Agents Get

A visitor sees a normal page from the theme with a plain form, a result count, and an ordered list. Each result can show a thumbnail, a linked title, a snippet, and the URL. The thumbnail is the page’s og:image from the index metadata, loaded lazily at a fixed size so the layout does not jump. If a page has no usable image, the thumbnail is simply omitted, with no placeholder and no WordPress lookup. Error states show a plain message for rate limiting and for an unavailable index.

The same URL answers machines. If a request sends Accept: application/json, the Worker returns the term and the results as JSON. My WebMCP plugin, which exposes site tools to AI agents running in the browser, uses that response for its search_posts tool. It has no database fallback, so an agent cannot reach MySQL through search either. And I advertise the new path in the Rank Math JSON-LD for the site, so a crawler that understands a site search action knows where to send a query.

Search for Agents also gives a site a discovery URL, /.well-known/search, that AI agents can use. It is separate from the public AI Search API and its MCP endpoint, which I left off. My Worker is the only client I run against the index.

Every term page also sends noindex, follow, so search engines follow its links but do not index thousands of useless result pages.

Measuring Search in Google Analytics

Moving the term into the path creates a measurement problem. Google Analytics detects site search from a query parameter such as ?s=, and my terms now live in a path like /s/network+storage/. The built-in report will not find them. So the results page sends two events on its own, through Cloudflare Zaraz and its zaraz.track call:

EventSent whenParameters
view_search_resultsThe results page finishes loading, including searches with zero resultssearch_term, search_results (the number of results)
select_search_resultA visitor clicks a resultsearch_term, result_position, link_url

I chose view_search_results because it is the name GA4 uses for site search. The second event is custom. Sending an event from the page is only half of it: in Zaraz, each event needs a trigger that matches its name and a GA4 event action that passes the parameters along. To report on the custom ones, register them as custom dimensions in GA4, and allow time for them to appear. The full snippet is in the how-to below.

What It Costs and What the Limits Are

Cost was a design constraint from day one, because AI Search stops being free to experiment with on December 1, 2026. Cloudflare publishes the numbers on its limits and pricing page, and they are the source for everything in this section. Every account receives included usage each month:

Included each monthAmount
Ingestion tokens5 million
Storage10 GB-month
Semantic, vector, or hybrid queries1,000
Full-text queries1,000

Usage beyond that is billed per million ingestion tokens, per GB-month of storage, and per thousand queries, with hybrid queries priced well above full-text ones. I am deliberately not quoting dollar figures here, because they are Cloudflare’s to change; read the pricing page on the day you decide. Storage is measured as the Markdown AI Search keeps for your pages, not your raw HTML, and the vectors and keyword index do not count toward it.

The plan you are on matters more for the first crawl than for the bill. The limits differ between Workers Free and Workers Paid:

LimitWorkers FreeWorkers Paid
Pages crawled per day500Unlimited
Pages per discover crawl100,000100,000
Files per instance100,0001 million, or 500,000 with hybrid search
Custom metadata fields per instance55
Included queries per month1,000 semantic and 1,000 full-text1,000 semantic and 1,000 full-text

The daily crawl cap is the one to remember. On the Free plan, a site with several thousand pages needs many days to finish its first crawl, and the number of pages you end up with is the lowest of the applicable limits. The Worker itself is billed under Workers pricing, where only requests that actually reach the Worker count. Because the route is limited to /s/*, the rest of your site traffic never touches it.

The design keeps the query bill proportional to the number of unique searches, not the number of searches. A cached term costs no query. Only a cache miss spends one, and three limits cap how many misses can happen: the per-IP gate, the site-wide gate, and the daily budget. The daily budget is a ceiling, not a forecast. Longer result cache lifetimes lower the number of misses, which is why I plan to raise the cache lifetime from one hour to 24 hours once the first crawl completes. Until then, a short lifetime keeps results from going stale while the index fills in.

What I Have Not Measured Yet

It is easy to oversell a rebuild like this, so here is what I do not know yet. I will not invent numbers for any of it:

  • The latency of a cache miss. A miss spends a billable query, so I have not timed it. The hard ceiling is the five second timeout.
  • The size of the index in GB, and the share of the site the first crawl has ingested.
  • The load on my origin with the new search running. The May load figures describe the old attack and the old mitigation, not this system, so they are not a before and after.
  • My actual Cloudflare bill for AI Search, Workers, KV, and Durable Objects. Billing starts December 1, so I will read the first invoice before I make any claim.

You can measure the same things on your own site. Send a unique term once and read the cache header and time to first byte for a miss, then repeat it for a hit. Watch AI Search usage in the dashboard, and compare origin request logs for /s/ against your old ?s= traffic.

How to Replace WordPress Search With Cloudflare Workers

Here is the build for a typical WordPress site. It assumes that your domain is on Cloudflare with the proxy enabled, that you can edit your server configuration or a .htaccess file, and that you can add a must-use plugin. You need Wrangler, Cloudflare’s command line tool for Workers, and Node.js on your computer. The Worker below is a trimmed reference version that I tested against mock bindings. It is not the exact Worker that runs on Martech Zone, so test it on your own site before you route traffic to it. Replace example.com everywhere with your domain.

Step 1: Turn On Search for Agents and Configure the Index

In the Cloudflare dashboard, find your domain, open the AI Search settings, and enable Search for Agents. That creates an AI Search instance and starts a crawl. Before the crawl goes far, open the instance settings and tune it using the website data source options:

  • Include your site only. Exclude /wp-admin/, /wp-json/, /wp-content/, /feed/, tag and author archives, and /s/. If you have a real content path named /search/, leave it included.
  • Set a content selector for your theme’s article wrapper so the crawler skips navigation and sidebars. Inspect a post to find it. Pages without that wrapper fall back to the full page.
  • Add up to five custom metadata fields from tags you already print, such as the title, the description, the og:image URL, and the published time.
  • Keep the public API and the MCP endpoint off unless you have a plan for them.
  • Choose hybrid search, a 24-hour sync interval, and note the instance name. You will need it in Step 3.

Let the first crawl run. On the Free plan, it can take many days because of the daily page limit.

Step 2: Let the Crawler Through Your Firewall

Check the instance job log. If it shows pages fetched, do nothing. If it shows 403 responses, a firewall or bot rule is blocking the crawler, and the website data source guide documents the skip rule to add. Add the narrowest rule the documentation describes, and do not loosen your WAF more broadly than that. On Martech Zone this step was not needed.

Step 3: Create the Worker Project

Create a folder and add the configuration below. It binds the search instance, the Durable Object gate, the two rate limiters, and KV. Every identifier in it is a placeholder.

name = "site-search"
main = "src/index.js"
compatibility_date = "2026-03-27"
workers_dev = false

routes = [
  { pattern = "example.com/s/*", zone_name = "example.com" },
  { pattern = "example.com/s",   zone_name = "example.com" },
]

[[ai_search]]
binding = "SEARCH"
instance_name = "search-for-agents-<ZONE_ID>"

[[durable_objects.bindings]]
name = "QUERY_GATE"
class_name = "QueryGate"

[[migrations]]
tag = "v1"
new_sqlite_classes = ["QueryGate"]

[[ratelimits]]
name = "RL_REQUESTS"
namespace_id = "1001"
simple = { limit = 30, period = 60 }

[[ratelimits]]
name = "RL_QUERIES"
namespace_id = "1002"
simple = { limit = 8, period = 60 }

[[kv_namespaces]]
binding = "SEARCH_KV"
id = "<KV_NAMESPACE_ID>"

[vars]
CACHE_VERSION = "v1"
RESULT_TTL = "3600"          # raise to 86400 after the first crawl
SHELL_TTL = "600"
MAX_CHUNKS = "30"
MAX_RESULTS = "15"
SEARCH_TIMEOUT_MS = "5000"
MAX_DAILY_QUERIES = "3000"
GATE_IP_PER_MIN = "8"
GATE_GLOBAL_PER_MIN = "120"
SHELL_URL = "https://example.com/s/"

[observability]
enabled = true

Create the KV namespace and paste its ID into the file:

npm install --save-dev wrangler
npx wrangler login
npx wrangler kv namespace create SEARCH_KV

Use the instance name that Cloudflare gave your instance in Step 1. The namespace_id values for the rate limiters are any unique integers in your account. See the AI Search Workers binding reference for the binding options.

Step 4: Write the Worker

Save this as src/index.js. It follows the request path from the previous sections, and it uses only index data to build results. It never calls WordPress, except to fetch the empty shell page.

// Site search on Cloudflare Workers + AI Search (reference version).
// Route: example.com/s/*  (and example.com/s)
// Rule: this code never calls WordPress except for the empty /s/ shell page.

const MAX_LEN = 100;
const MAX_WORDS = 12;
const JUNK = [
  /https?:|www\./i,                     // URLs
  /<|>|\{|\}|\\|`/,                     // markup and shell characters
  /\b(select|union|insert|update|delete|drop)\b.+\b(from|into|table|select)\b/i,
  /(.)\1{5,}/,                          // aaaaaa
  /\b[a-z0-9]{25,}\b/i,                 // random token blobs
];

export function normalize(raw) {
  if (typeof raw !== "string" || raw.length > MAX_LEN * 4) return "";
  let q = raw.normalize("NFKC").replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f]/g, " ");
  if (JUNK.some((re) => re.test(q))) return "";
  q = q.toLowerCase().replace(/[^\p{L}\p{N}+\-.#&' ]+/gu, " ");
  q = q.split(/\s+/).map((w) => w.replace(/^[\-.&']+|[\-.&']+$/g, "")).filter(Boolean).join(" ");
  if (q.length < 2 || q.length > MAX_LEN || q.split(" ").length > MAX_WORDS) return "";
  return /[\p{L}\p{N}]/u.test(q) ? q : "";
}

const slug = (q) => q.split(" ").map(encodeURIComponent).join("+");
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));

const redirect = (to) => new Response(null, { status: 301, headers: { location: to, "cache-control": "public, max-age=86400" } });
const plain = (status, body, extra = {}) => new Response(body, { status, headers: { "content-type": "text/plain", ...extra } });
const tooMany = () => plain(429, "Too many searches. Try again in a minute.", { "retry-after": "60", "cache-control": "no-store" });

// Exact per-IP and site-wide limits on cache misses (Durable Object).
export class QueryGate {
  constructor(state) { this.win = 0; this.n = 0; }
  async fetch(request) {
    const limit = Number(new URL(request.url).searchParams.get("limit")) || 1;
    const w = Math.floor(Date.now() / 60000);
    if (w !== this.win) { this.win = w; this.n = 0; }
    if (this.n >= limit) return new Response("0");
    this.n += 1;
    return new Response("1");
  }
}
async function take(env, name, limit) {
  const stub = env.QUERY_GATE.get(env.QUERY_GATE.idFromName(name));
  return (await (await stub.fetch(`https://gate/?limit=${limit}`)).text()) === "1";
}

// One result per page, best chunk first. Only index data is used.
// Check what item.key looks like for your instance and adjust the URL mapping.
export function collapse(chunks, host, limit = 15) {
  const byUrl = new Map();
  for (const c of chunks || []) {
    const meta = (c.item && c.item.metadata) || {};
    let u;
    try { u = new URL((c.item.key || "").startsWith("http") ? c.item.key : `https://${c.item.key}`); } catch { continue; }
    if (u.hostname !== host || /^\/(s|wp-admin|wp-json|wp-content|feed|tag|author)(\/|$)/.test(u.pathname)) continue;
    const url = `https://${host}${u.pathname.replace(/\/index(\.[^/]*)?\.md$/i, "/").replace(/\.md$/i, "/")}`;
    const prev = byUrl.get(url);
    if (prev && prev.score >= c.score) continue;
    byUrl.set(url, {
      url,
      title: meta.title || url,
      snippet: String(meta.description || c.text || "").replace(/\s+/g, " ").slice(0, 220),
      image: meta.image || "",
      score: c.score,
    });
  }
  return [...byUrl.values()].sort((a, b) => b.score - a.score).slice(0, limit);
}

function listHtml(q, results) {
  if (!results.length) return `<p>No results for “${esc(q)}”.</p>`;
  const items = results.map((r) =>
    `<li>${r.image ? `<img src="${esc(r.image)}" width="120" height="63" loading="lazy" alt="">` : ""}` +
    `<h2><a href="${esc(r.url)}">${esc(r.title)}</a></h2><p>${esc(r.snippet)}</p><cite>${esc(r.url)}</cite></li>`).join("");
  return `<p>${results.length} results for “${esc(q)}”</p><ol class="search-list">${items}</ol>`;
}

export default {
  async fetch(request, env) {
    if (request.method !== "GET" && request.method !== "HEAD") return plain(405, "Method not allowed");
    const url = new URL(request.url);
    const host = url.hostname;

    // /s/ or /s/?q=term
    if (url.pathname === "/s" || url.pathname === "/s/") {
      if (!url.searchParams.has("q")) return fetch(request);            // empty shell from origin
      const norm = normalize(url.searchParams.get("q"));
      return norm ? redirect(`/s/${slug(norm)}/`) : plain(404, "Not found");
    }

    // /s/{term}/
    const m = /^\/s\/([^/]+)\/?$/.exec(url.pathname);
    if (!m) return plain(404, "Not found");
    let raw;
    try { raw = m[1].split("+").map(decodeURIComponent).join(" "); } catch { return plain(404, "Not found"); }
    const norm = normalize(raw);
    if (!norm) return plain(404, "Not found");
    const canonical = `/s/${slug(norm)}/`;
    if (url.pathname !== canonical || url.search) return redirect(canonical);   // no cache busting

    const ip = request.headers.get("cf-connecting-ip") || "unknown";
    if (!(await env.RL_REQUESTS.limit({ key: ip })).success) return tooMany();

    // 1. Result cache: Cache API (this location), then KV (global).
    const cacheKey = new Request(`https://cache.invalid/${env.CACHE_VERSION}/${slug(norm)}`);
    let results, cached = true;
    const hit = await caches.default.match(cacheKey);
    if (hit) results = await hit.json();
    if (!results) {
      const kv = await env.SEARCH_KV.get(`${env.CACHE_VERSION}:${norm}`, "json");
      if (kv) results = kv;
    }

    // 2. Miss: spend a query only if every gate allows it.
    if (!results) {
      cached = false;
      if (!(await env.RL_QUERIES.limit({ key: ip })).success) return tooMany();
      if (!(await take(env, `ip:${ip}`, Number(env.GATE_IP_PER_MIN))) ||
          !(await take(env, "global", Number(env.GATE_GLOBAL_PER_MIN)))) return tooMany();
      const day = `budget:${new Date().toISOString().slice(0, 10)}`;
      const used = Number(await env.SEARCH_KV.get(day)) || 0;
      if (used >= Number(env.MAX_DAILY_QUERIES)) return plain(503, "Search is temporarily unavailable.", { "retry-after": "300", "cache-control": "no-store" });
      await env.SEARCH_KV.put(day, String(used + 1), { expirationTtl: 172800 });

      const found = await Promise.race([
        env.SEARCH.search({
          query: norm,
          ai_search_options: { retrieval: { max_num_results: Number(env.MAX_CHUNKS) } },
        }),
        new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), Number(env.SEARCH_TIMEOUT_MS))),
      ]).catch(() => null);
      if (!found) return plain(503, "Search is temporarily unavailable.", { "retry-after": "60", "cache-control": "no-store" });
      results = collapse(found.chunks, host, Number(env.MAX_RESULTS));
      const ttl = Number(env.RESULT_TTL);
      await env.SEARCH_KV.put(`${env.CACHE_VERSION}:${norm}`, JSON.stringify(results), { expirationTtl: Math.max(60, ttl) });
      await caches.default.put(cacheKey, new Response(JSON.stringify(results), { headers: { "cache-control": `max-age=${ttl}` } }));
    }

    const headers = { "x-search-cache": cached ? "hit" : "miss", "x-robots-tag": "noindex, follow" };
    if ((request.headers.get("accept") || "").includes("application/json")) {
      return new Response(JSON.stringify({ q: norm, results }), { headers: { ...headers, "content-type": "application/json", vary: "accept" } });
    }

    // 3. Render: inject results into the cached, term-free WordPress shell.
    const shellReq = new Request(env.SHELL_URL, { cf: { cacheTtl: Number(env.SHELL_TTL), cacheEverything: true } });
    const shell = await (await fetch(shellReq)).text();
    const html = shell
      .replace('<div id="search-results"></div>', `<div id="search-results">${listHtml(norm, results)}</div>`)
      .replace(/(<input[^>]*name="q"[^>]*?)(\s*\/?>)/, `$1 value="${esc(norm)}"$2`);
    return new Response(html, { headers: { ...headers, "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=300", vary: "accept" } });
  },
};

A few details are worth knowing. The Worker maps each chunk’s item.key to a URL on your host, so check what that key looks like for your instance and adjust the mapping if it differs. The QueryGate class is the Durable Object that counts cache misses. And the function that collapses chunks into pages is where you would add your own excluded paths or a minimum score.

Deploy it:

npx wrangler deploy

Step 5: Create the Search Page Shell in WordPress

In WordPress, create a page with the slug s and a title such as Search. Add a Custom HTML block that holds the form, an empty results container, and the tracking script from Step 9. The Worker looks for the exact empty container and fills the q input, so keep these two elements as written:

<form role="search" method="get" action="/s/">
  <label class="screen-reader-text" for="search-q">Search</label>
  <input type="search" id="search-q" name="q" minlength="2" maxlength="100" required>
  <button type="submit">Search</button>
</form>
<div id="search-results"></div>

The Worker passes the plain /s/ request through to this page, caches it, and injects results for each term. Make this page noindex. In Rank Math, open the page’s Advanced tab and choose No Index. If you use a different SEO plugin, use its equivalent setting.

Style the results list in your theme. The Worker outputs an ordered list with the class search-list, and each item has an optional img, an h2 link, a paragraph, and a cite. Give the image a fixed width and height so it does not shift the layout. A UI that matches your theme will matter more than any other detail.

Step 6: Redirect Old Search URLs Before WordPress Runs

Search URLs of the form /?s=term are already in bookmarks, search results, and bot lists. Redirect the homepage version at the web server, so PHP never starts. On nginx, add a map in the http context and a rule in the server context:

# http context
map $request_uri $search_qs_redirect {
    default "";
    "~^/\?(?:[^#]*&)?s=([^&#]+)" /s/$1/;
}

# server context
if ($search_qs_redirect) {
    return 301 https://example.com$search_qs_redirect;
}

On Apache, put this in .htaccess, above the WordPress block:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{QUERY_STRING} (^|&)s=([^&]+)
RewriteRule ^$ /s/%2/? [R=301,L]

This only matches the homepage, so admin searches such as /wp-admin/edit.php?s= keep working. If you cannot edit the server configuration, the must-use plugin in Step 8 includes a PHP fallback. It is slower, because WordPress has to start, but it still avoids the search query.

Step 7: Replace the Search Form

Every search form on your site should submit to /s/ with a field named q, not s. WordPress builds its forms through the get_search_form filter, so one filter covers the theme and the classic search widget. The Search block builds its own form, so it needs a second filter. Put both in the must-use plugin from the next step.

Step 8: Switch Off Native Search Queries

Create wp-content/mu-plugins/edge-search.php. A must-use plugin loads before regular plugins and cannot be deactivated by accident. This one does four things: it redirects leftover ?s= requests, swaps the forms, empties the SQL search clause for visitors, and returns a 404 for any search that still reaches WordPress.

<?php
/**
 * Plugin Name: Edge Search
 * Description: Sends search to the Cloudflare Worker and keeps native search away from MySQL.
 */

// 1. Fallback redirect: /?s=term to /s/term/ before the main query runs.
add_action( 'after_setup_theme', function () {
	if ( is_admin() || wp_doing_ajax() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
		return;
	}
	$path = wp_parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH );
	if ( '/' !== $path || ! isset( $_GET['s'] ) ) {
		return;
	}
	$term   = is_string( $_GET['s'] ) ? trim( wp_unslash( $_GET['s'] ) ) : '';
	$target = mb_strlen( $term ) >= 2
		? '/s/' . urlencode( mb_strtolower( mb_substr( $term, 0, 100 ) ) ) . '/'
		: '/s/';
	wp_redirect( home_url( $target ), 301 );
	exit;
}, 0 );

// 2. Every search form submits to /s/ with the field "q".
add_filter( 'get_search_form', function () {
	$id = wp_unique_id( 'edge-search-' );
	return '<form role="search" method="get" class="search-form" action="' . esc_url( home_url( '/s/' ) ) . '">'
		. '<label class="screen-reader-text" for="' . esc_attr( $id ) . '">Search</label>'
		. '<input type="search" id="' . esc_attr( $id ) . '" name="q" minlength="2" maxlength="100" required>'
		. '<button type="submit" class="search-submit">Search</button></form>';
}, 999 );

// The Search block builds its own form, so replace its output.
add_filter( 'render_block_core/search', function () {
	return get_search_form( array( 'echo' => false ) );
} );

// 3. No search SQL for visitors. Editors keep the admin and REST search.
add_filter( 'posts_search', function ( $search ) {
	return current_user_can( 'edit_posts' ) ? $search : '';
}, 999 );

// 4. Any front-end search that still reaches WordPress becomes a 404.
add_action( 'parse_query', function ( $query ) {
	if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
		return;
	}
	$query->set( 's', '' );
	$query->is_search = false;
	$query->set_404();
} );

Check your theme and plugins for anything else that searches. Live search plugins and theme AJAX search handlers often run their own query. If a theme feature loads results as you type, close its AJAX action for visitors, or disable the feature. On Martech Zone I closed the theme’s live search for everyone who cannot edit posts, because it ran a PHP query with the search term.

Step 9: Add Search Tracking

Put this script in the Custom HTML block of the search page, below the results container. It reads the term from the path and sends the two events from the measurement section with zaraz.track. If you use plain gtag instead of Zaraz, replace the zaraz.track calls with gtag('event', name, params).

<script>
(function () {
  var m = /^\/s\/([^\/]+)\/?$/.exec(location.pathname);
  if (!m) return;
  var term = decodeURIComponent(m[1].replace(/\+/g, ' '));

  function track(name, params, tries) {
    tries = tries || 0;
    if (window.zaraz && typeof zaraz.track === 'function') {
      zaraz.track(name, params);
    } else if (tries < 20) {
      setTimeout(function () { track(name, params, tries + 1); }, 500);
    }
  }

  window.addEventListener('load', function () {
    track('view_search_results', {
      search_term: term,
      search_results: document.querySelectorAll('#search-results li').length
    });
  });

  document.addEventListener('click', function (e) {
    var a = e.target.closest && e.target.closest('#search-results li a[href]');
    if (!a) return;
    var li = a.closest('li');
    var pos = Array.prototype.indexOf.call(li.parentNode.children, li) + 1;
    track('select_search_result', {
      search_term: term,
      result_position: pos,
      link_url: a.href
    });
  }, true);
})();
</script>

Then, in the Zaraz dashboard, add a trigger for each event name and attach it to a GA4 event action that passes the parameters through. Use DebugView in GA4 to confirm that both events arrive.

Step 10: Test Before You Trust It

Run these checks from a terminal. Each one proves a different layer:

# 1. The old URL redirects without PHP
curl -sI "https://example.com/?s=Network+Storage" | grep -iE "^(HTTP|location)"

# 2. The Worker canonicalizes and answers
curl -sI "https://example.com/s/?q=Network+Storage" | grep -iE "^(HTTP|location)"
curl -sI "https://example.com/s/network+storage/" | grep -iE "^(HTTP|x-search-cache|x-robots-tag)"

# 3. A second request is a cache hit
curl -sI "https://example.com/s/network+storage/" | grep -i "x-search-cache"

# 4. JSON for agents
curl -s -H "accept: application/json" "https://example.com/s/network+storage/"

# 5. Junk is rejected without an index call
curl -sI "https://example.com/s/http%3A%2F%2Fevil.test/" | head -1

Then watch the AI Search usage and the Worker analytics for the first few days, and look at your origin access log. Term URLs should not appear in it while the Worker route is live. When the first crawl finishes, raise RESULT_TTL to 86400 and deploy again.

Search Without the Risk

Search did not need to be dangerous. It was dangerous because WordPress runs it inside the one component that cannot scale. Move the index, the cache, the limits, and the rendering to the edge, and a bot typing random words is a problem for Cloudflare’s network instead of for your database.

The honest summary of where we are: search works, it is protected in layers, and the first crawl is still filling the index. Real numbers will be worth sharing once there is a bill and a week of traffic to read. If you try the build on your own site, start with the cheap parts, the form swap and the redirect, and prove that nothing reaches MySQL before you add anything else.

Try it for yourself and tell me what you find.

Try Martech Zone Search

Frequently Asked Questions

Does WordPress ever touch the database during a search?

Not on Martech Zone. The Worker builds results from the index and a cached copy of an empty page. In the build I describe, WordPress still serves that one empty page like any other page, but it never runs a search query.

How fresh are the search results?

They are as fresh as the last crawl. The AI Search crawler syncs every 24 hours, and nothing in WordPress pushes a new post into the index, so a post you publish now will not appear until the next sync.

Can I do this on the Cloudflare free plan?

You can try it on Workers Free, but the crawl is limited to 500 pages per day, so a large site takes many days to index. Check the current limits on the AI Search pricing page, because billing for AI Search begins on December 1, 2026.

Do I need Turnstile or changes to my WAF?

No. I use neither for search, and I did not change any WAF, challenge, or Bot Management rule. The Worker enforces the limits. You only need a firewall exception if the crawler reports 403 errors.

Will search result pages hurt my SEO?

They should not. The shell page and every term page send noindex, so search engines follow the links but do not index the results. Your real content pages are unaffected.

Why not use a search plugin instead?

A plugin can be a good choice if you want to keep everything inside WordPress. The trade is that the work stays on your server. This design moves it to the edge, which is what keeps a flood of searches away from your database.

What if the Worker stops working?

Term URLs fall through to the origin, which in my setup returns a static unavailable page and never searches content. The rest of the site is unaffected.

How much will it cost?

I do not know yet, and I will not guess. Billing starts December 1, 2026. Cache hits cost no index query, and the daily budget caps misses. Read your own usage in the Cloudflare dashboard after the first week.

Related Articles