Fix 404s From AI-Made-Up Links to Your Site
ChatGPT and other AI tools sometimes invent URLs on your website that never existed, so visitors land on a 404 page. This prompt finds these fake-link 404s in your data, decides which deserve a redirect and turns your 404 page into a helpful page that still keeps the visitor.
Example input
This is exactly what we gave the model. You replace it with your own details.
- Website: https://www.example.net (SaaS for event ticketing, with docs and a blog) - Platform: Next.js on Vercel; docs on a docs subfolder - Where I can see 404s: Vercel logs, GA4 page_not_found events, Search Console - Paste 20-100 recent 404 URLs with referrer and hit count if possible: URL | hits (30 days) | top referrer /docs/api/v2/create-event | 212 | chatgpt.com /docs/api/v2/refund-ticket | 96 | chatgpt.com /blog/how-to-sell-tickets-on-instagram-2024 | 58 | perplexity.ai /docs/integrations/zapier-setup | 44 | chatgpt.com /pricing/enterprise-plan | 31 | gemini.google.com /docs/webhooks/event-cancelled | 27 | copilot.microsoft.com /wp-login.php | 340 | (none) /.env | 120 | (none) /blog/event-marketing-checklist-pdf | 19 | chatgpt.com /docs/api/create-event | 15 | (none) - My real URL patterns (examples of correct URLs): /docs/api/events/create/ /docs/api/tickets/refund/ /docs/integrations/zapier/ /docs/webhooks/ /pricing/ /blog/sell-tickets-on-instagram/ /blog/event-marketing-checklist/ - What my current 404 page shows: A plain 'Page not found' message and a link to the homepage. It returns a real 404 status.
Real output
Pasted straight from the model. We did not fix a word.
Quick summary: About half of your 404 hits (502 of 962) come from AI tools. Six AI-invented URLs have one clear real page each, and they cover 444 of those 502 hits, so they get 301s. Two URLs are medium confidence and go to the smart 404 page. The other 460 hits are bot probes, so ignore them. I found no typos in this sample. Per the facts you gave, the plan is a few cheap fixes now, then data, before spending more.
Before I start: 5 quick questions (I used my best guess for each)
- Are your docs part of the same Next.js app, using the App Router? Guess: yes. If the docs are a separate tool served under
/docsthrough a rewrite, keep the redirects in the main app'snext.config. Next.js runs redirects before rewrites, so they still work. - Is
trailingSlash: trueset in yournext.config? Guess: yes, because all your real URLs end with/. - Did your site ever use URLs like
/docs/api/create-eventor/blog/how-to-sell-tickets-on-instagram-2024? Guess: no, so I label them AI-invented. If they did exist, they are "old URLs that moved". The action (301) stays the same. - Are you planning a real API v2 with
/docs/api/v2/...URLs? Guess: no. - Do you have a site search page (for example
/search?q=)? Guess: no, so the new 404 page searches your sitemap by itself.
1. 404 triage table
| 404 URL | Hits | Referrer | Type | Likely intended page | Confidence | Action |
|---|---|---|---|---|---|---|
| /docs/api/v2/create-event | 212 | chatgpt.com | AI-invented (wrong format: invented v2 + verb-noun) | /docs/api/events/create/ | High | 301 |
| /docs/api/v2/refund-ticket | 96 | chatgpt.com | AI-invented (same wrong format) | /docs/api/tickets/refund/ | High | 301 |
| /blog/how-to-sell-tickets-on-instagram-2024 | 58 | perplexity.ai | AI-invented (real topic, extra "how-to" and "2024") | /blog/sell-tickets-on-instagram/ | High | 301 |
| /docs/integrations/zapier-setup | 44 | chatgpt.com | AI-invented (extra "-setup") | /docs/integrations/zapier/ | High | 301 |
| /pricing/enterprise-plan | 31 | gemini.google.com | AI-invented (sub-page that doesn't exist) | /pricing/ (Enterprise part, guess) | Medium | Smart 404 (shows /pricing/ as top match) |
| /docs/webhooks/event-cancelled | 27 | copilot.microsoft.com | AI-invented (sub-page that doesn't exist) | /docs/webhooks/ | Medium | Smart 404 (shows /docs/webhooks/ as top match) |
| /blog/event-marketing-checklist-pdf | 19 | chatgpt.com | AI-invented (extra "-pdf") | /blog/event-marketing-checklist/ | High | 301 |
| /docs/api/create-event | 15 | (none) | Likely AI-invented, referrer lost (guess, see Q3) | /docs/api/events/create/ | High | 301 (covered by the same pattern rule) |
| /wp-login.php | 340 | (none) | Bot probe (WordPress login scan; your site is Next.js) | None | n/a | Ignore, keep 404 |
| /.env | 120 | (none) | Bot probe (scan for secret files) | None | n/a | Ignore, keep 404 (check it stays 404) |
Why some rows are not "High":
- /pricing/enterprise-plan: The visitor wanted Enterprise pricing. I don't know if
/pricing/shows an Enterprise tier. If it doesn't, a redirect would suggest a plan you don't have. The smart 404 puts/pricing/at the top anyway, so the visitor is one click away. If you confirm the tier exists and hits stay at 10 or more next month, change it to a 301. - /docs/webhooks/event-cancelled: This could be a real webhook event, or the AI made it up. If you really send an "event cancelled" webhook and it isn't clearly documented, write that section. That has lasting value; a redirect doesn't.
- /docs/api/create-event (no referrer): It uses the same wrong
verb-nounformat as the ChatGPT URLs. AI apps, desktop apps and copy-paste often send no referrer, so this is a guess.
2. Redirect rules (Next.js on Vercel)
// next.config.js — merge into your existing config (keep your other settings)
/** @type {import('next').NextConfig} */
const nextConfig = {
trailingSlash: true, // guess (Q2): you already use trailing slashes
async redirects() {
return [
// Pattern 1: AI format "/docs/api/[vN/]<verb>-<noun>"
// Catches /docs/api/v2/create-event, /docs/api/v1/create-event, /docs/api/create-event
// Add a verb ONLY after you check the real page exists, e.g. (create|update)
{
source: '/docs/api/:version(v\\d+)?/:action(create)-event',
destination: '/docs/api/events/:action/',
permanent: true,
},
{
source: '/docs/api/:version(v\\d+)?/:action(refund)-ticket',
destination: '/docs/api/tickets/:action/',
permanent: true,
},
// Pattern 2: AI format "/docs/integrations/<name>-setup"
// Add names ONLY for integrations that have a real page, e.g. (zapier|mailchimp)
{
source: '/docs/integrations/:name(zapier)-setup',
destination: '/docs/integrations/:name/',
permanent: true,
},
// Single high-confidence blog URLs.
// No blog-wide pattern on purpose: slugs vary too much, and a wrong
// redirect is worse than a good 404.
{
source: '/blog/how-to-sell-tickets-on-instagram-2024',
destination: '/blog/sell-tickets-on-instagram/',
permanent: true,
},
{
source: '/blog/event-marketing-checklist-pdf',
destination: '/blog/event-marketing-checklist/',
permanent: true,
},
// NOT redirected on purpose:
// /pricing/enterprise-plan, /docs/webhooks/event-cancelled -> medium confidence -> smart 404
// /wp-login.php, /.env -> bot probes -> keep the 404
// No catch-all redirect to the homepage. Ever.
];
},
};
module.exports = nextConfig;
Notes:
permanent: truesends a 308, which Google treats the same as a 301. If you want a literal 301, replacepermanent: truewithstatusCode: 301.- Query strings are kept, so
?utm_source=chatgpt.comcarries through to the real page, and GA4 still credits the AI tool. - A URL without the trailing slash may take 2 hops: first the slash is added, then the redirect runs. That's fine.
- If you launch a real API v2 later (Q4), remove the
:version(v\\d+)?part first. Real v2 URLs like/docs/api/v2/events/create/wouldn't match theverb-nounformat anyway, so the risk is low.
Test after deploy:
# Should show 308 hops ending at the real page with HTTP 200
curl -sIL https://www.example.net/docs/api/v2/create-event | grep -iE '^(HTTP|location)'
curl -sIL https://www.example.net/docs/api/create-event | grep -iE '^(HTTP|location)'
curl -sIL https://www.example.net/blog/event-marketing-checklist-pdf | grep -iE '^(HTTP|location)'
# Must return a real 404 (no redirect, no 200)
curl -sI https://www.example.net/pricing/enterprise-plan | head -1
curl -sI https://www.example.net/docs/webhooks/event-cancelled | head -1
curl -sI https://www.example.net/.env | head -1
curl -sI https://www.example.net/this-page-does-not-exist-123 | head -1
3. Smart 404 page: copy and code
Page copy
- Headline: Sorry, we can't find that page
- Line under it: There's no page at
/docs/webhooks/event-cancelled. The link may be old or mistyped, or the page may never have existed. - AI note (shown only to visitors from an AI tool or with no referrer; hidden for visitors from your own site or other sites): Came from an AI assistant? Tools like ChatGPT, Perplexity, Gemini and Copilot sometimes make up links that look real. The page you want probably exists under a different address. Try the matches below.
- Search box label: Search example.net. It is pre-filled with words from the URL, for example
webhooks event cancelled. - Best matches: Up to 5 pages from your sitemap. For your two smart-404 URLs:
/docs/webhooks/event-cancelled→ top match Webhooks (/docs/webhooks/)/pricing/enterprise-plan→ top match Pricing (/pricing/)
- Popular pages: Docs links on
/docs/...URLs; site links everywhere else. - About example.net (guess wording, edit to match your positioning): Ticketing software for event organizers. Sell tickets, manage events and refunds, and connect your tools with our API, webhooks and integrations like Zapier.
- Footer links: Go to the homepage · Contact support
Code (App Router)
Step 1: Create app/_components/SmartNotFound.tsx
'use client';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';
declare global {
interface Window {
gtag?: (...args: unknown[]) => void;
}
}
type Page = { url: string; title: string; tokens: string[] };
// Words that don't help search
const STOP_WORDS = new Set([
'a', 'an', 'the', 'to', 'of', 'on', 'in', 'for', 'and', 'or', 'how', 'with',
'your', 'my', 'is', 'docs', 'blog', 'www', 'html', 'htm', 'php', 'pdf',
]);
// AI tools, matched against the referrer and utm_source
const AI_SOURCES: Array<[RegExp, string]> = [
[/chatgpt\.com|chat\.openai\.com/, 'chatgpt'],
[/perplexity/, 'perplexity'],
[/gemini\.google\.com|bard\.google\.com/, 'gemini'],
[/copilot\.microsoft\.com/, 'copilot'],
[/claude\.ai/, 'claude'],
[/deepseek\.com/, 'deepseek'],
[/grok\.com/, 'grok'],
[/meta\.ai/, 'meta_ai'],
];
const POPULAR = {
docs: [
{ url: '/docs/api/events/create/', title: 'API: Create an event' },
{ url: '/docs/api/tickets/refund/', title: 'API: Refund a ticket' },
{ url: '/docs/webhooks/', title: 'Webhooks' },
{ url: '/docs/integrations/zapier/', title: 'Zapier integration' },
],
site: [
{ url: '/pricing/', title: 'Pricing and plans' },
{ url: '/docs/', title: 'Documentation' }, // guess: your docs home
{ url: '/blog/sell-tickets-on-instagram/', title: 'How to sell tickets on Instagram' },
{ url: '/blog/event-marketing-checklist/', title: 'Event marketing checklist' },
],
};
function toWords(path: string): string[] {
let text = path;
try {
text = decodeURIComponent(path);
} catch {}
return text
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter((w) => w && !STOP_WORDS.has(w) && !/^v\d+$/.test(w) && !/^\d+$/.test(w));
}
function stem(w: string): string {
if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss')) return w.slice(0, -1);
return w;
}
function sharedSegments(a: string, b: string): number {
const x = a.split('/').filter(Boolean);
const y = b.split('/').filter(Boolean);
let n = 0;
while (n < x.length && n < y.length && x[n] === y[n]) n++;
return n;
}
function titleFor(path: string): string {
const last = path.split('/').filter(Boolean).pop() ?? '';
const text = last.replace(/-/g, ' ');
return text ? text[0].toUpperCase() + text.slice(1) : 'Home';
}
async function readSitemap(path: string): Promise<{ isIndex: boolean; locs: string[] }> {
const res = await fetch(path);
if (!res.ok) return { isIndex: false, locs: [] };
const xml = new DOMParser().parseFromString(await res.text(), 'application/xml');
return {
isIndex: xml.documentElement.nodeName === 'sitemapindex',
locs: Array.from(xml.getElementsByTagName('loc')).map((n) => n.textContent?.trim() ?? ''),
};
}
// Builds a small search index from /sitemap.xml (also handles a sitemap index)
async function loadPages(): Promise<Page[]> {
const root = await readSitemap('/sitemap.xml');
let locs = root.locs;
if (root.isIndex) {
const children = await Promise.all(
locs.map((l) => readSitemap(new URL(l, window.location.origin).pathname)),
);
locs = children.flatMap((c) => c.locs);
}
return locs.filter(Boolean).map((loc) => {
const url = new URL(loc, window.location.origin).pathname;
return { url, title: titleFor(url), tokens: toWords(url).map(stem) };
});
}
function getSource(): string {
const utm = new URLSearchParams(window.location.search).get('utm_source') ?? '';
const ref = document.referrer;
const signal = `${ref} ${utm}`.toLowerCase();
const ai = AI_SOURCES.find(([pattern]) => pattern.test(signal));
if (ai) return ai[1];
if (!ref) return 'none';
try {
return new URL(ref).hostname === window.location.hostname ? 'internal' : 'other';
} catch {
return 'other';
}
}
function trackClick(from: string, to: string) {
window.gtag?.('event', 'not_found_click', {
not_found_path: from.slice(0, 100),
target_path: to.slice(0, 100),
});
}
export default function SmartNotFound() {
const pathname = usePathname() ?? '/';
const [query, setQuery] = useState(() => toWords(pathname).join(' '));
const [pages, setPages] = useState<Page[] | null>(null);
const [source, setSource] = useState<string | null>(null);
useEffect(() => {
loadPages().then(setPages).catch(() => setPages([]));
}, []);
useEffect(() => {
setQuery(toWords(pathname).join(' '));
const src = getSource();
setSource(src);
// Replaces your current page_not_found tag (remove the old one to avoid double counts)
window.gtag?.('event', 'page_not_found', {
not_found_path: pathname.slice(0, 100), // GA4 value limit is 100 characters
not_found_source: src, // chatgpt | perplexity | gemini | ... | internal | other | none
});
}, [pathname]);
const results = useMemo(() => {
const q = toWords(query).map(stem);
if (!pages || q.length === 0) return [];
return pages
.map((p) => {
const hits = q.filter((w) => p.tokens.includes(w)).length;
const score = hits === 0 ? 0 : hits + 0.5 * sharedSegments(pathname, p.url);
return { ...p, score };
})
.filter((p) => p.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, 5);
}, [query, pages, pathname]);
const popular = pathname.startsWith('/docs') ? POPULAR.docs : POPULAR.site;
const showAiNote = source !== null && source !== 'internal' && source !== 'other';
return (
<main style={{ maxWidth: 720, margin: '64px auto', padding: '0 20px' }}>
<h1>Sorry, we can't find that page</h1>
<p>
There's no page at <code>{pathname}</code>. The link may be old or mistyped,
or the page may never have existed.
</p>
{showAiNote && (
<p role="note">
<strong>Came from an AI assistant?</strong> Tools like ChatGPT, Perplexity, Gemini
and Copilot sometimes make up links that look real. The page you want probably
exists under a different address. Try the matches below.
</p>
)}
<form role="search" onSubmit={(e) => e.preventDefault()}>
<label htmlFor="nf-search">Search example.net</label>{' '}
<input
id="nf-search"
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
autoComplete="off"
/>
</form>
<h2>Best matches</h2>
{pages === null ? (
<p>Searching…</p>
) : results.length > 0 ? (
<ul>
{results.map((r) => (
<li key={r.url}>
<Link href={r.url} onClick={() => trackClick(pathname, r.url)}>
{r.title}
</Link>{' '}
<small>{r.url}</small>
</li>
))}
</ul>
) : (
<p>No close matches. Try fewer or different words, or use the links below.</p>
)}
<h2>Popular pages</h2>
<ul>
{popular.map((l) => (
<li key={l.url}>
<Link href={l.url} onClick={() => trackClick(pathname, l.url)}>
{l.title}
</Link>
</li>
))}
</ul>
<h2>About example.net</h2>
<p>
Ticketing software for event organizers. Sell tickets, manage events and refunds,
and connect your tools with our API, webhooks and integrations like Zapier.
</p>
<p>
<Link href="/">Go to the homepage</Link> ·{' '}
{/* guess: change to your real support URL */}
<Link href="/contact/">Contact support</Link>
</p>
</main>
);
}
Step 2: Replace app/not-found.tsx
import SmartNotFound from './_components/SmartNotFound';
// Next.js serves this for every unmatched URL with a real 404 status
// and adds a noindex tag automatically.
export default function NotFound() {
return <SmartNotFound />;
}
Step 3: Keep real 404s (no soft 404s) in your docs and blog routes
- In dynamic routes like
app/docs/[...slug]/page.tsxandapp/blog/[slug]/page.tsx, callnotFound()when the page doesn't exist. Never show "not found" text with a 200 status. - If those pages are prebuilt with
generateStaticParams, addexport const dynamicParams = false;so unknown slugs return a 404 automatically. - If a route has a
loading.tsx, Next.js may start streaming with a 200 status beforenotFound()runs. Check those routes withcurl -I. If you get a 200, run the "does this page exist?" check before anything streams, or removeloading.tsxfrom that route.
Step 4: Remove your old page_not_found GA4 tag so each 404 is counted once. The new component sends the event with extra data.
If you use the Pages Router (Q1 wrong): Use the same component in pages/404.tsx, and read the path from useRouter().asPath after the page loads instead of usePathname(). pages/404 also returns a real 404.
4. Monthly monitoring checklist
One-time setup
- In GA4 → Admin → Custom definitions, create event-scoped custom dimensions
not_found_path,not_found_sourceandtarget_path. They only collect data from the day you create them. - In GA4 → Explore, build a Free-form report called "AI 404s". Filter: event name =
page_not_found. Rows:not_found_path. Columns:not_found_source. Value: Event count. Save it. - Optional: in GA4 → Admin → Channel groups, add an "AI assistants" channel with source matching
chatgpt|perplexity|gemini|copilot|claude|deepseek|grok|meta\.ai. This shows AI visits that land on real pages, including visits through your new redirects. - Keep in mind: the 6 redirected URLs will now show as 308 in Vercel logs, not 404, and their visitors appear in GA4 on the real pages. Don't read the drop in 404s as "AI traffic stopped".
- Start a simple sheet with these columns: Month | AI 404 hits | Unique AI 404 URLs | No-referrer hits on wrong-format URLs | Internal 404s | Redirects added.
Every month
- Count. From the "AI 404s" report, add up the hits from AI sources. Separately, count
nonehits on wrong-format URLs (like/docs/api/create-event) andinternalhits. - Fix internal 404s first.
not_found_source = internalmeans a broken link on your own site. That's a real problem you control, not an AI problem. - Review the top 10 AI 404 URLs with these rules:
- 301 only if: 10 or more hits this month, it also appeared last month, and there is one clear real page (high confidence).
- Pattern rule only if the same wrong format shows up on 3 or more URLs, and only for destinations that exist.
- Everything else stays on the smart 404.
- Check the smart 404 is helping. Compare
not_found_clickwithpage_not_foundper URL. If a busy URL gets fewer than about 20% clicks (my guess at a starting target), the matching is weak, or the content the visitor wanted doesn't exist. - Look for content gaps. If AI tools keep inventing a page for something you really offer (for example, an event-cancelled webhook), write or improve that real page. Don't create pages only to catch AI clicks.
- Check the redirects still work. Run the
curl -sILtests. Every destination must end at a 200 with no long chains. If you rename a docs page, update its redirect destination. - Search Console. In Pages, the "Soft 404" count must be zero. 404s for AI-invented URLs in "Not found (404)" are normal and don't hurt your site, so don't use "Validate fix" on them.
- Status check.
curl -Ia made-up URL. It must return 404. - Probes. Confirm
/.envand/wp-login.phpstill return 404, and leave them out of your counts. Bots don't run GA4, so they mostly show up in Vercel logs. Optional: if they clutter your logs, block them with a Vercel Firewall custom rule. - Use the right source. Vercel log retention may be short on your plan, so use GA4 for monthly totals and Vercel for spot checks. GA4 numbers will be lower than Vercel's because of consent banners, ad blockers and bots.
Thresholds (my suggestion, a guess you can tune)
- Baseline (this month): 502 AI-related 404 hits, including the 15 with no referrer. The new redirects cover 444, so expect about 58 per month to remain (the two medium-confidence URLs).
- Add more redirects only if the remaining AI 404s go above 100 per month for 2 months in a row and the URLs have clear destinations.
- Spend more (for example, automatic pattern matching in Next.js middleware that only redirects to URLs listed in your sitemap) only if AI 404s rise 3 months in a row or pass 300 per month after the redirects.
- Review at month 6 and month 12. Google's John Mueller expects a small rise for 6 to 12 months, then a decline. If your numbers fall, stop adding rules. Keep the smart 404 page, and keep any redirect that still gets hits.
The prompt
First lines open so you can see how it is built. The rest opens after purchase.
#ROLE You are a technical SEO and UX expert. Help me handle 404 errors caused by AI tools that invent links to my website (hallucinated URLs). #INPUTS Fill in every line. Leave a line blank if you don't know it. - Website: [WEBSITE URL] - Platform: [e.g., WordPress, Shopify, Next.js] - Where I can see 404s: [e.g., server logs, GA4 page-not-found report, Search Console, a 404 monitoring plugin]
How to use it
- Buy, then open it in your account.
- Copy the prompt into ChatGPT, Claude or Gemini.
- Replace the 6 inputs with your product.
- Run it. Use the output. Re-run with a different tone if you like.
Pro tips
- Include the referrer column. It's the quickest way to tell AI-invented links from bot probes.
- Only redirect when the intended page is obvious and the link keeps getting hits. A wrong redirect is worse than a good 404.
- Improve the 404 page first. It helps every lost visitor, not only the ones from AI tools.
Before you buy
- Will it work for my product?
- Yes, if you can fill the 6 inputs. If the output is bad with your inputs, email us: we fix the prompt and refund you.
- Do I download a file?
- No. It lives in your account with a copy button, and updates when we improve it.
- Which model is best?
- Best on Claude. Works in ChatGPT, Claude and Gemini.
Works well with this
Prompts people use in the same campaign.
More in AI Search & Bots
Buying more than two? Lifetime is cheaper.
Every prompt, every category, forever. $59 once. Nothing to download, nothing to renew.
This prompt
$3$7
- ✓ Instant access in your account, with a copy button
- ✓ Example input and real output included
- ✓ 7-day money-back, no form
Or get every prompt, forever
Lifetime Access · $59 $149 — all categories, all future prompts, rewrites included.
Get lifetime accessCard or PayPal · taxes at checkout · nothing to download
Not the one you need?
Browse every prompt by category and sub-category.