Prompt to build an internal linking agent from a site map

Short answer

This prompt asks an AI assistant to read your sitemap, count links between pages, find pages that few others link to, and write link-plan.csv with proposed links. Each proposal names the source sentence, the anchor text and the target page. Nothing is changed until you approve the plan.

Last reviewed

Key facts

  • The link counts exclude navigation and footer links, so a page linked only from the footer counts as weakly linked.
  • Anchor text must come from words already on the source page. The assistant may not invent a sentence.
  • Proposals are a CSV you review. Applying them is a separate, approved step.
  • Test status: the reference script was run on webexport.online (60 pages from its sitemap). It found 8 pages with fewer than 2 inbound body links, among them the contact, terms and privacy pages that are linked only from the footer, and wrote 21 candidate links to link-suggestions.csv. The assistant step that picks sentences and edits the pages was not run.

The prompt

Paste this into Claude Code, Cursor, Codex or another AI coding assistant with your project folder open, and replace everything in square brackets first. See how to run it in each tool.

Plan internal links
You are improving internal links on a site. The site is [LIVE_URL_OR_FOLDER]. Pages are at most [MAX_PAGES: 150].

READ
- The sitemap at [LIVE_URL]/sitemap.xml, or every .html file in [EXPORT_FOLDER].
- The body text of each page. Ignore navigation, header and footer links when you count links.

STEP 1: GRAPH
Build a table with one row per page: path, title, number of body links going out, number of body links coming in. Save it as link-graph.csv.

STEP 2: FIND
List pages with fewer than 2 incoming body links. Say which are weak on purpose (legal pages, thank-you pages) and leave those out.

STEP 3: PROPOSE
For each remaining weak page, propose up to [LINKS_PER_PAGE: 3] new links from other pages that cover a related topic. For each proposal write one row in link-plan.csv: source path, target path, the exact existing sentence on the source page, the words in it to use as the anchor, and one line of reasoning.
- Use only words already in the sentence. Do not write new sentences.
- Never link a page to itself or add a link that already exists.
- Maximum [MAX_NEW_LINKS_PER_SOURCE: 3] new links on any source page.

STEP 4: STOP
Do not edit any page. Wait for my approval of link-plan.csv.

RULES
- Do not change navigation, header, footer or sitemap.
- Do not use exact keyword anchors repeatedly. Vary anchors across pages.
- If scripts/linkgraph.mjs exists, use it for steps 1 and 2.

How to run it

  1. Decide which pages are weak on purpose and tell the assistant in the prompt.
  2. Run the prompt and open link-plan.csv. Delete any row whose sentence you would not link from.
  3. Approve the plan and ask the assistant to apply it in one commit per source page.
  4. Rebuild the link graph and check that the weak pages moved.

Run it without a paid key

This script builds the link graph from a sitemap, counts only body links, and suggests candidate sources by shared words in page titles. It is a starting list for the assistant, not a decision. It reads up to the page limit you give it, five at a time.

scripts/linkgraph.mjs
// Usage: node linkgraph.mjs https://example.com 80
// Builds an internal link graph from sitemap.xml pages and writes link-suggestions.csv for pages with few inbound links.
import fs from 'node:fs';

const [base, limit = '80'] = process.argv.slice(2);
if (!base) { console.error('Usage: node linkgraph.mjs https://example.com [limit]'); process.exit(1); }
const origin = new URL(base).origin;
const get = async (u) => { try { const r = await fetch(u, { signal: AbortSignal.timeout(15000), headers: { 'user-agent': 'linkgraph/1.0' } }); return r.ok ? await r.text() : ''; } catch { return ''; } };
const locs = (x) => [...x.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1]);
let urls = locs(await get(`${origin}/sitemap.xml`));
if (urls.length && urls.every((u) => u.endsWith('.xml'))) urls = (await Promise.all(urls.map(async (u) => locs(await get(u))))).flat();
urls = [...new Set(urls)].filter((u) => u.startsWith(origin)).slice(0, Number(limit));

const norm = (u) => { const x = new URL(u); return x.pathname.replace(/\/$/, '') || '/'; };
const STOP = new Set('a an and are as at be by for from how in is it of on or the to what with your you export site website page prompt guide'.split(' '));
const pages = {};
const queue = [...urls];
await Promise.all(Array.from({ length: 5 }, async () => {
  while (queue.length) {
    const u = queue.shift();
    const html = await get(u);
    const main = html.replace(/<(nav|footer|header|script|style)[\s\S]*?<\/\1>/gi, ' ');
    const out = new Set([...main.matchAll(/<a\s[^>]*href=["']([^"'#]+)["']/gi)].map((m) => { try { const x = new URL(m[1], u); return x.origin === origin ? norm(x.href) : null; } catch { return null; } }).filter(Boolean));
    const title = (html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] ?? '').replace(/&amp;/g, '&').replace(/\s*\|[^|]*$/, '').replace(/\s+/g, ' ').trim();
    pages[norm(u)] = { title, out, terms: new Set(title.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2 && !STOP.has(w))) };
  }
}));

const inbound = Object.fromEntries(Object.keys(pages).map((p) => [p, []]));
for (const [p, d] of Object.entries(pages)) for (const t of d.out) if (t !== p && inbound[t]) inbound[t].push(p);

const rows = [['target', 'inbound_now', 'candidate_source', 'shared_terms', 'already_links']];
const weak = Object.keys(pages).filter((p) => p !== '/' && inbound[p].length < 2);
for (const t of weak) {
  const cands = Object.keys(pages).filter((s) => s !== t).map((s) => ({ s, shared: [...pages[t].terms].filter((w) => pages[s].terms.has(w)) })).filter((c) => c.shared.length).sort((a, b) => b.shared.length - a.shared.length).slice(0, 3);
  for (const c of cands) rows.push([t, inbound[t].length, c.s, c.shared.join(' '), pages[c.s].out.has(t)]);
}
fs.writeFileSync('link-suggestions.csv', rows.map((r) => r.map((v) => `"${v}"`).join(',')).join('\n'));
console.log(`${Object.keys(pages).length} pages read, ${weak.length} with fewer than 2 inbound links, ${rows.length - 1} candidate links written to link-suggestions.csv`);
for (const t of weak.slice(0, 10)) console.log(`${inbound[t].length} inbound  ${t}`);

The Firecrawl path

When a site is too large to fetch yourself, the map endpoint lists its URLs. It also takes a search term and, according to the docs, orders results by relevance to it. That gives you a quick list of pages on a topic to consider as link sources. The crawl endpoint returns each page's links when you add the links format to scrapeOptions, so you can build the graph from its output.

terminal
curl -s -X POST https://api.firecrawl.dev/v2/map \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://example.com","search":"hosting","limit":50}'

Verify the result

After the links are applied, count them again and confirm the plan did what it said.

terminal
node scripts/linkgraph.mjs https://preview.example.com 150
git diff --stat
grep -c "" link-plan.csv
  • The number of pages with fewer than 2 incoming body links is lower than before.
  • The diff touches only the source pages in link-plan.csv, and only inside the approved sentences.
  • Every new link returns a 200 when you click it.

What can go wrong

  • Shared title words suggest related pages, but two pages can share a word and have nothing to do with each other. Read each row.
  • Too many links on one page dilute them. The per-page cap exists for this reason.
  • Linking from a page that is itself blocked or thin adds little. Prefer source pages that get visits.

Frequently asked questions

What is an orphan page?

A page that no other page links to. Search engines mostly find pages through links, so an orphan is easy to miss. A page linked only from the footer is close to an orphan.

Why leave out navigation links?

Every page has the same navigation, so those links say little about which pages relate. Links inside the body text are a stronger signal of topic.

Can the assistant pick anchors freely?

The prompt limits it to words already in a sentence on the source page. That keeps the copy yours and keeps the anchors natural.

Does this help an exported site?

Yes. Exports often keep a flat list of pages. A link plan after the move is a cheap way to rebuild topic structure.

Official documentation

Free tools for this job

Start with the files

Prompts work best on a WebExport download of your site. Paste your public URL into the export form and get a ZIP. The Free plan covers 1 site, 5 exports a month, 15 pages and 20 MB per export. Professional is a $9.99 one-time purchase with unlimited pages.