We launched StitchSEO, our free one-page SEO audit, on Product Hunt today. While checking our own launch claims we found two bugs in how it read robots.txt.

The check looked like this:

const blocksAll = /user-agent:\s*\*[\s\S]*?disallow:\s*\/\s*(\n|$)/i.test(robotsTxt)
  && !/allow:\s*\//i.test(robotsTxt);

The second test was meant to spot an Allow: / line. But the string Disallow: / contains allow: /. So whenever the first half matched, the second half cancelled it, and a site that blocked every crawler still passed.

For AI crawlers we built a regex per bot:

new RegExp(`user-agent:\\s*${bot}[\\s\\S]*?disallow:\\s*/\\s*(\\n|$)`, 'i')

The lazy [\s\S]*? happily runs past the end of the bot's own group. With this file, GPTBot was reported as blocked:

User-agent: GPTBot
Allow: /

User-agent: BadBot
Disallow: /

Read the file the way a crawler does: use the group that names you, or the * group if none does, and remember that consecutive User-agent lines share the rules below them.

export function blockedFromSite(robotsTxt: string, bot: string): boolean {
  const groups: { agents: string[]; rules: string[] }[] = [];
  let readingAgents = false;
  for (const line of robotsTxt.split(/\r?\n/)) {
    const m = /^\s*([a-z-]+)\s*:\s*([^#]*)/i.exec(line);
    if (!m) continue;
    const key = m[1].toLowerCase();
    const value = m[2].trim();
    if (key === 'user-agent') {
      if (!readingAgents) groups.push({ agents: [], rules: [] });
      groups[groups.length - 1].agents.push(value.toLowerCase());
      readingAgents = true;
    } else if (key === 'allow' || key === 'disallow') {
      groups[groups.length - 1]?.rules.push(`${key}:${value.replace(/^\/\*$/, '/')}`);
      readingAgents = false;
    }
  }
  const own = groups.filter((g) => g.agents.includes(bot.toLowerCase()));
  const rules = (own.length ? own : groups.filter((g) => g.agents.includes('*'))).flatMap((g) => g.rules);
  return rules.includes('disallow:/') && !rules.includes('allow:/');
}

It only answers one question, whether a bot is shut out of the whole site. It doesn't evaluate path rules.

We added ten small test cases, including both files above. If you have a robots.txt check of your own, try them on it.

The tool is at saraswatistitch.com/seo-audit if you want to break it.

Written with AI assistance. Code and behaviour checked against our repository.

原文来源:dev.to