> For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt.

# Robots.txt & RFC 9309: The Robots Exclusion Protocol

A `robots.txt` file instructs web crawlers which URL paths on an origin they are allowed or disallowed from fetching. Published in September 2022, **RFC 9309** standardized the core parsing and matching rules of the Robots Exclusion Protocol across major search engines.

This guide focuses on the specification details that most frequently trip up engineering teams in production:

- **Section 2.1:** How parsers group rules and match `User-agent` product tokens.
- **Section 2.2.2:** How `Allow` and `Disallow` rules compete using longest-match (octet length) precedence—and why `Allow` wins ties.
- **Section 2.3:** How HTTP status codes (`2xx`, `3xx`, `4xx`, `5xx`) on `/robots.txt` alter crawler behavior across an entire domain.

:::warning\[`robots.txt` Is Not an Access Control Mechanism]
`robots.txt` is a public advisory file—not authentication, authorization, or a firewall. Anyone can fetch `/robots.txt` directly, and non-compliant bots will ignore it altogether.
:::

## File Location and Origin Scope

The file must reside at the top-level root of the origin, be named `/robots.txt` (all lowercase), and be served as UTF-8 `text/plain`:

```text
https://example.com/robots.txt
```

Because `robots.txt` is scoped strictly per **authority** (scheme + host + port), `https://example.com/robots.txt`, `https://www.example.com/robots.txt`, and `https://api.example.com/robots.txt` are completely separate files. Placing a file in a subdirectory such as `/booking/robots.txt` has zero effect.

A minimal file that explicitly allows all crawlers to fetch every path:

```txt title="robots.txt"
User-agent: *
Disallow:
```

An empty `Disallow:` value declares that no paths are blocked, making your intent clearer than serving an empty zero-byte file.

## How Crawlers Parse `robots.txt`

### 1. Grouping Rules

A **group** begins with one or more consecutive `User-agent` lines followed by `Allow` and `Disallow` rules. The group ends when the parser encounters the next `User-agent` line (after at least one rule) or reaches the end of the file:

```txt
User-agent: ExampleBot
Disallow: /private/
Allow: /private/preview.html
```

Any `Allow` or `Disallow` rules appearing above the very first `User-agent` line do not belong to a valid group and are ignored. Comments start with `#` and can occupy an entire line or trail after a directive:

```txt
# Block administrative routes from crawlers
User-agent: *
Disallow: /admin/ # Internal staff portal
```

### 2. Matching the `User-agent` Group

Each `User-agent` line specifies a crawler **product token** (letters, hyphens, and underscores). Parsers match product tokens using **case-insensitive substring matching**.

For example, the following group matches `HotelBot`, `hotelbot`, or `Mozilla/5.0 (compatible; HotelBot/1.0)`:

```txt
User-agent: HotelBot
Disallow: /internal/
```

When a crawler evaluates `robots.txt`, it selects its active rule set using two precedence rules:

1. **Specific match overrides wildcard (`*`):** If one or more groups explicitly match the crawler's product token, the crawler merges **only** those matching groups and completely ignores the `User-agent: *` fallback group.
2. **Wildcard fallback:** If no specific `User-agent` group matches, the crawler falls back to `User-agent: *`.

```txt
User-agent: Googlebot
Disallow: /private/

User-agent: *
Disallow: /tmp/
```

In the example above, `Googlebot` matches the specific `Googlebot` group and **only** obeys `Disallow: /private/`—it is **not** blocked from `/tmp/` unless you repeat `Disallow: /tmp/` inside the `Googlebot` group.

### 3. Resolving `Allow` vs. `Disallow` (Longest-Match Precedence)

Once the crawler selects its applicable group, it compares the target URL's path and query string against every rule in that group:

1. A rule matches from the **first octet** of the path (`/…`).
2. When multiple rules match a URL, the **most specific rule**—the pattern with the **longest matching byte/octet length**—wins.
3. **Tie-breaker:** If a matching `Allow` rule and `Disallow` rule have the exact same pattern length, **`Allow` wins**.

```txt
User-agent: *
Disallow: /booking/
Allow: /booking/confirmation.html
```

| Target URL Path              | Outcome     | Reason                                                     |
| ---------------------------- | ----------- | ---------------------------------------------------------- |
| `/booking/search`            | **Blocked** | Matches `/booking/` (9 chars)                              |
| `/booking/confirmation.html` | **Allowed** | Matches both, but `Allow` is longer (26 chars vs. 9 chars) |
| `/rooms/suite`               | **Allowed** | Matches no rule; allowed by default                        |

If an `Allow` and `Disallow` rule share the exact same length, RFC 9309 specifies that `Allow` takes precedence:

```txt
User-agent: *
Disallow: /public/
Allow: /public/
```

Here `/public/` is allowed—though in practice you should avoid writing contradictory duplicate patterns.

## Pattern Matching: Prefixes, `*`, and `$`

By default, every rule pattern is a **prefix match**: `Disallow: /private/` matches `/private/`, `/private/a`, and `/private/a/b.html`.

RFC 9309 standardizes two special wildcard characters inside patterns:

- **`*`**: Matches zero or more instances of any character.
- **`$`**: Anchors the match to the end of the URL path/query.

```txt
User-agent: *
Disallow: /*.json$
Allow: /api/public.json
```

This configuration blocks any URL ending in `.json` except `/api/public.json` (which wins via longest match). Note that crawlers evaluate percent-encoded URI paths—keep non-ASCII or reserved characters properly percent-encoded when writing rules.

Note also that `/robots.txt` itself is always implicitly allowed; writing `Disallow: /` never prevents a crawler from fetching `/robots.txt`.

## Production Example: Hospitality / E-Commerce Website

A hotel or e-commerce site typically has high-value landing pages that should be crawled alongside transactional, session-bound, or faceted filter URLs that waste crawl budget:

```txt title="robots.txt for hotel.example"
User-agent: *

# Explicitly allow high-value search landing directories
Allow: /rooms/
Allow: /locations/
Allow: /offers/

# Block administrative, API, and transactional checkout routes
Disallow: /admin/
Disallow: /api/
Disallow: /checkout/
Disallow: /account/
Disallow: /booking/search
Disallow: /booking/confirmation
Disallow: /*?session=
Disallow: /*?utm_

Sitemap: https://hotel.example/sitemap.xml
```

### Avoiding Overly Broad Prefix Blocks

Suppose your site uses the following URL structure:

- `/rooms/deluxe` — Public room detail page (must be indexed)
- `/booking/packages` — Public promotional packages page (must be indexed)
- `/booking/search` — Interactive date/guest picker form (no search value)
- `/booking/confirmation` — Post-checkout receipt page (must not be crawled)

Block the specific transactional paths rather than the entire `/booking/` prefix:

```txt
# ✅ Good: targets only the non-indexable transactional endpoints
User-agent: *
Disallow: /booking/search
Disallow: /booking/confirmation
```

Avoid writing `Disallow: /booking/` if public landing pages like `/booking/packages` live under that prefix.

Similarly, be careful with the **"deny-all, allow-selectively"** pattern:

```txt
# ⚠️ Caution: blocks the homepage (/) and every path outside /rooms/
User-agent: *
Disallow: /
Allow: /rooms/
```

Because `Disallow: /` has length 1, it blocks the homepage (`/`) and every top-level asset (CSS, JS, images, and pages) that does not start with `/rooms/`. Unless you are intentionally locking down an entire subdomain except one subfolder, block specific paths instead.

## How HTTP Status Codes on `/robots.txt` Affect Crawling

Crawlers react not only to the text inside `/robots.txt`, but also to the **HTTP status code** returned when fetching it (RFC 9309 Section 2.3):

| HTTP Status Class                          | Crawler Interpretation                 | Impact on Site Crawling                                                                             |
| ------------------------------------------ | -------------------------------------- | --------------------------------------------------------------------------------------------------- |
| **`2xx` (Success)**                        | File fetched successfully              | Crawler parses and enforces the directives in the response body.                                    |
| **`3xx` (Redirect)**                       | Follow redirect chain                  | Crawlers follow at least **5 redirect hops**. Avoid redirect loops or long chains on `/robots.txt`. |
| **`4xx` (Client Error, e.g. `404`)**       | No restrictions exist _(except `429`)_ | Crawler assumes **full permission to crawl the entire site** without restrictions.                  |
| **`5xx` (Server Error) / Network Timeout** | Temporary server failure               | Crawler assumes a **complete `Disallow: /` across the entire site** until `/robots.txt` recovers.   |

:::important\[Monitor `/robots.txt` Uptime Separately]
A transient `503 Service Unavailable` or origin timeout on `/robots.txt` can halt Googlebot crawling across your entire domain, whereas accidentally returning `404` removes all crawl protections at once. Monitor `/robots.txt` status codes, `Content-Type`, and CDN caching in your production alerting.
:::

Crawlers typically cache `/robots.txt` for up to **24 hours**. Whenever you deploy a rule change, verify the live response through your CDN and reverse proxy (`curl -i https://example.com/robots.txt`) and purge edge caches if needed.

## Security Reminder: `robots.txt` Does Not Protect Sensitive Routes

Never list secret URLs, private tokens, or unauthenticated admin endpoints in `robots.txt` assuming it will hide them. Because `/robots.txt` is world-readable, attackers and security scanners routinely scrape it first to discover sensitive paths.

To protect `/admin/`, `/account/`, or private APIs:

- Enforce **authentication and authorization** on the server.
- Use `<meta name="robots" content="noindex">` or `X-Robots-Tag: noindex` when a public page must be excluded from search results (and keep it crawlable in `robots.txt` so the crawler can read the `noindex` directive).

## Pre-Deployment Checklist

1. Fetch `https://your-domain.example/robots.txt` on the production hostname and confirm it returns `HTTP 200`, UTF-8 encoding, and `Content-Type: text/plain`.
2. Audit specific `User-agent` blocks alongside `User-agent: *`—remembering that a specific match **replaces** the `*` block rather than inheriting from it.
3. Test critical landing pages, assets (JS/CSS/images), and transactional routes against the longest-match rule.
4. Check equal-length rule ties (`Allow` wins over `Disallow`).
5. Verify query parameters, percent-encoding, trailing slashes, and CDN redirect rules.
6. Declare your [Sitemap.xml](https://nhanbe.id.vn/building-for-the-web/web-seo/sitemap-xml.md) using an absolute URL and confirm the sitemap path itself is not blocked by `Disallow`.
7. Use the interactive [Robots + Sitemap Inspector](https://nhanbe.id.vn/building-for-the-web/web-seo/robots-sitemap-inspector.md) to test path rules against search and AI crawlers (`Googlebot`, `GPTBot`, `ClaudeBot`).

## References

- [RFC 9309 — Robots Exclusion Protocol (IETF Official Specification)](https://www.rfc-editor.org/rfc/rfc9309.html)
- [RFC 9309 on IETF Datatracker](https://datatracker.ietf.org/doc/rfc9309/)
