BYTESLIP ← Back
Knowledge Base // Tutorial 125

noindex vs robots.txt: Robots Meta Tags, X-Robots-Tag and Snippet Controls

Difficulty: Medium ~25 min robots.txt · .htaccess · Python

robots.txt and noindex look like two ways to do the same thing. They aren’t, and using them together can backfire. robots.txt controls crawling. noindex controls indexing, and Google only sees it if it’s allowed to crawl the page. This guide shows which one to use for each job, how to send noindex for PDFs from .htaccess, how the snippet rules work, and a Python checker that applies Google’s robots.txt rules to your URLs.

Crawl rules versus index rules Four tiles: robots.txt for crawling, meta noindex, X-Robots-Tag header, snippet rules. ROBOTS.TXT CRAWL META NOINDEX X-ROBOTS -TAG SNIPPET RULES
Safety // Read First

Warnings

ImportantDon’t block a page in robots.txt to get it out of Google. Google says a blocked page can still be indexed if other pages link to it, and Google never sees a noindex on a page it can’t crawl. robots.txt is also not security: Google says to use password protection for private files. Back up .htaccess before editing it.

Checklist // Before You Start

What You Need

How this was tested: robots_check.py got all six of Google’s own rule-precedence examples right (longest match wins, and allow wins a tie). It picked the googlebot group over *, ignored a googlebot-news group, and merged two googlebot groups, as Google’s spec describes. On a local Apache 2.4.71 server, the .htaccess block below added X-Robots-Tag: noindex to a PDF. The script flagged a noindex page that robots.txt blocks, and a nosnippet + max-snippet conflict. It applied googlebot: nofollow and ignored a header for another bot. Python 3.13 and 3.12 gave identical output. On a live LiteSpeed site, it showed three pages crawlable and indexable, and the site’s 404 page carrying noindex.

Walkthrough // Steps 01–07

Pick the tool → noindex → headers → snippets → check → confirm

Most small sites need very few of these rules. The point is to avoid the ones that cancel each other out.

  1. Step 1: Pick the right tool for the job

    • Keep a page out of search results: noindex in a meta tag or an X-Robots-Tag header. The page must stay crawlable.
    • Stop crawling of unimportant or near-duplicate URLs: robots.txt. Google says not to use it to hide pages from Search.
    • Keep something private: password protection. Google says not every crawler obeys robots.txt.
    • Hide a URL fast: Search Console’s Removals tool. Google says a request lasts only about six months, so also add noindex or delete the page.

    Google doesn’t support noindex inside robots.txt. robots.txt syntax and sitemaps are covered in Clean URLs, a Correct sitemap.xml and a Sane robots.txt.

  2. Step 2: Add noindex to HTML pages

    <meta name="robots" content="noindex">

    Use name="googlebot" to address only Google. Google says that when tags conflict, the more restrictive rule applies. When a robots tag and a googlebot tag are both present, Googlebot follows the negative rules from both. Typical candidates on a small site are thank-you pages, internal search results and drafts you’ve uploaded to preview.

  3. Step 3: Send noindex for PDFs and other files from .htaccess

    Non-HTML files can’t carry a meta tag, so send the rule as an HTTP header. This is Google’s Apache example, wrapped so it does nothing if mod_headers is missing:

    # --- Keep PDFs out of search results (they can still be crawled) ---
    <IfModule mod_headers.c>
      <FilesMatch "\.pdf$">
        Header set X-Robots-Tag "noindex"
      </FilesMatch>
    </IfModule>
    curl -sI https://example.com/files/manual.pdf | grep -i x-robots-tag

    You should see X-Robots-Tag: noindex. For HTML pages, the meta tag is simpler. Security headers set in .htaccess the same way are covered in HTTPS, HSTS and Security Headers.

  4. Step 4: Control snippets and previews

    These rules change how a page appears in results; they don’t remove it:

    <meta name="robots" content="max-snippet:20, max-image-preview:large">
    • max-snippet:[number]: the maximum text snippet length in characters. 0 means no snippet; -1 lets Google choose. Google says it also limits how much text can be used as direct input for AI Overviews and AI Mode.
    • max-image-preview:large: allows a large image preview, up to the width of the viewport. The other values are none and standard.
    • nosnippet: no text snippet or video preview. If a page has both nosnippet and max-snippet, the stricter nosnippet wins.
    • data-nosnippet: keeps part of a page out of snippets. It works only on span, div and section elements:
    <p>This text can be shown in a snippet
    <span data-nosnippet>and this part would not be shown</span>.</p>

    Google lists noarchive as no longer used, because cached links no longer exist.

  5. Step 5: Save the checker

    Google uses the longest matching rule, and allow wins a tie. Python’s built-in urllib.robotparser doesn’t: in our test, with Disallow: /a/ followed by Allow: /a/b/, it called /a/b/x blocked, while Google’s rules allow it. This script follows Google’s rules:

    #!/usr/bin/env python3
    """Show every crawl and index rule Googlebot would see for each URL.
    
    Usage: python3 robots_check.py URL [URL ...]
    Checks robots.txt (Google's longest-match rules), the X-Robots-Tag header,
    and robots/googlebot meta tags, then warns about combinations that backfire.
    """
    import re, sys, urllib.error, urllib.request
    from html.parser import HTMLParser
    from urllib.parse import urlsplit
    
    UA = "Mozilla/5.0 (compatible; robots-check/1.0)"
    
    def fetch(url):
        req = urllib.request.Request(url, headers={"User-Agent": UA})
        try:
            r = urllib.request.urlopen(req, timeout=20)
        except urllib.error.HTTPError as e:
            r = e
        return r.status, r.headers, r.read(2_000_000).decode("utf-8", "replace")
    
    def googlebot_rules(robots_txt):
        groups, agents, rules, last_was_rule = [], [], [], False
        for raw in robots_txt.splitlines():
            line = raw.split("#", 1)[0].strip()
            if ":" not in line:
                continue
            field, value = (x.strip() for x in line.split(":", 1))
            field = field.lower()
            if field == "user-agent":
                if last_was_rule:
                    groups.append((agents, rules))
                    agents, rules = [], []
                m = re.match(r"[a-z_*-]+", value.lower())
                agents.append(m.group(0) if m else value.lower())
                last_was_rule = False
            elif field in ("allow", "disallow") and agents:
                if value:
                    rules.append((field, value))
                last_was_rule = True
        if agents:
            groups.append((agents, rules))
        for token in ("googlebot", "*"):
            picked = [r for a, rs in groups if token in a for r in rs]
            if picked or any(token in a for a, _ in groups):
                return picked
        return []
    
    def allowed(rules, path):
        best = None
        for kind, pat in rules:
            rx = re.escape(pat).replace(r"\*", ".*")
            if rx.endswith(r"\$"):
                rx = rx[:-2] + "$"
            if re.match(rx, path):
                key = (len(pat), kind == "allow")
                if best is None or key > best[0]:
                    best = (key, kind, pat)
        return (True, "no matching rule") if best is None else (best[1] == "allow", f"{best[1]}: {best[2]}")
    
    class Meta(HTMLParser):
        def __init__(self):
            super().__init__()
            self.tags = []
        def handle_starttag(self, tag, attrs):
            a = dict(attrs)
            name = (a.get("name") or "").lower()
            if tag == "meta" and name in ("robots", "googlebot"):
                self.tags.append((name, a.get("content") or ""))
    
    def directives(text):
        return [d.strip().lower() for d in text.split(",") if d.strip()]
    
    robots_cache = {}
    for url in sys.argv[1:]:
        parts = urlsplit(url)
        root = f"{parts.scheme}://{parts.netloc}"
        if root not in robots_cache:
            code, _, body = fetch(root + "/robots.txt")
            robots_cache[root] = googlebot_rules(body) if code == 200 else []
        path = (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
        ok, why = allowed(robots_cache[root], path)
        status, headers, body = fetch(url)
        found = []
        for h in headers.get_all("X-Robots-Tag") or []:
            m = re.match(r"\s*([\w-]+)\s*:\s*(.*)", h)
            if m and m.group(1).lower() not in ("max-snippet", "max-image-preview", "max-video-preview", "unavailable_after"):
                if m.group(1).lower() != "googlebot":
                    continue
                h = m.group(2)
            found += [("X-Robots-Tag", d) for d in directives(h)]
        if "html" in (headers.get("Content-Type") or ""):
            p = Meta()
            p.feed(body)
            found += [(f'meta name="{n}"', d) for n, c in p.tags for d in directives(c)]
        names = {d.split(":")[0] for _, d in found}
        print(f"\n{url}\n  HTTP {status}   robots.txt: {'allowed' if ok else 'BLOCKED'} ({why})")
        for where, d in found:
            print(f"  {where}: {d}")
        if not found:
            print("  no robots meta tag or X-Robots-Tag (default: index, follow)")
        if not ok and names & {"noindex", "none"}:
            print("  WARNING: robots.txt blocks this URL, so Google never sees its noindex.")
        if not ok and not names & {"noindex", "none"}:
            print("  NOTE: blocked from crawling, but the URL can still be indexed if linked.")
        if "nosnippet" in names and "max-snippet" in names:
            print("  NOTE: nosnippet and max-snippet together: the stricter nosnippet wins.")
        if ok and status == 200 and names & {"noindex", "none"}:
            print("  Google drops this URL from results the next time it crawls it.")
  6. Step 6: Run it on the URLs that matter

    python3 ~/robots_check.py https://example.com/ https://example.com/files/manual.pdf

    Output from our test server (its address is replaced with example.com here):

    https://example.com/drafts/next-post/
      HTTP 200   robots.txt: BLOCKED (disallow: /drafts/)
      meta name="robots": noindex
      WARNING: robots.txt blocks this URL, so Google never sees its noindex.
    
    https://example.com/files/manual.pdf
      HTTP 200   robots.txt: allowed (no matching rule)
      X-Robots-Tag: noindex
      Google drops this URL from results the next time it crawls it.
    
    https://example.com/tutorials/snippet-demo/
      HTTP 200   robots.txt: allowed (no matching rule)
      meta name="robots": max-snippet:50
      meta name="robots": max-image-preview:large
      meta name="googlebot": nosnippet
      NOTE: nosnippet and max-snippet together: the stricter nosnippet wins.

    The first result is the classic mistake: a draft folder blocked in robots.txt and also tagged noindex. To get it out of Search, remove the Disallow, let Google crawl the page and see the noindex. Once it’s gone from results, you can delete the page or put it behind a password.

  7. Step 7: Confirm in URL Inspection

    In URL Inspection, run Test live URL and read two lines: Crawl allowed? (robots.txt) and Indexing allowed? (noindex). Google warns that if robots.txt blocks a page, Indexing allowed? always shows “Yes”, because Google can’t see the noindex. To see the page Google fetched, open View tested page and search the HTML for noindex.

Pro Tip

AI training is a separate switch

Questions // FAQ

FAQ

Can I put noindex in robots.txt?

No. Google says noindex in robots.txt isn’t supported. Use the meta tag or the X-Robots-Tag header.

How long until a noindexed page disappears?

Google drops it the next time Googlebot crawls the page and sees the rule. For less important pages that can take months. URL Inspection’s Request indexing asks for a recrawl.

Does nofollow in the robots meta tag hide the page?

No. Page-level nofollow tells Google not to follow the links on that page. It doesn’t affect whether the page itself is indexed.

Do other search engines follow these rules?

Google notes that other search engines may not treat every rule the same way. Check each engine’s own documentation for the rules you rely on.

Keep Reading
Sources // Verified

Official docs

Meta tag, X-Robots-Tag, every rule, conflicts, data-nosnippet and the Apache examples: Robots meta tag specifications. noindex and robots.txt together, and recrawl timing: Block Search indexing with noindex. What robots.txt is for: Introduction to robots.txt. Rule precedence and groups: How Google interprets robots.txt. Google-Extended: Google’s common crawlers. Removals: Removals tool. Crawl allowed and Indexing allowed: URL Inspection tool. Python’s parser: urllib.robotparser.

← All Tutorials Byteslip Apps