Building an Automated Website Audit That Fetches Politely: robots.txt, Rate Limits and Scope
An automated website audit fetches someone else's site, often from your servers. A synthetic fetch plan covering scope and permission, SSRF checks, robots.txt per RFC 9309, rate limits, backoff on 429/503 and the cases where the right move is to stop.


Text equivalent. Bounded website audits Teaching diagram • Permission, scope and a request budget 1 / Permission + origins Operator-approved scope Origin = scheme + IDNA host + port No automatic ports / subdomains 2 / Exact vs subtree Exact / = homepage only /services subtree includes /services/x NOT /services-admin; reject ambiguous paths 3 / Check destination Every request, retry + redirect hop Validate resolved addresses Pinned connect required; NOT in helpers 4 / robots.txt BEFORE any page request Fetch robots through the same scope/address gate. Parse 2xx with a conformant RFC 9309 parser. 404/410: proceed in scope. 401/403: STOP. 429: DEFER. 5xx/network: NO PAGES this run. Robots disallow: do not fetch that URL. Out-of-scope redirect or >5 hops: ABORT. This stricter response policy is not authorisation; the helpers do NOT parse robots rules. 5 / Shared per-origin bounds One concurrent request; >=1 s between requests Coordinate across audits; decompressed byte/time caps Budget ALL requests: robots, sitemaps, pages, assets, redirects and retries. Design only. 6 / Fetch response 429/503: full Retry-After (never shortened) If delay > time left: DEFER origin; no early retry No header: bounded backoff; max 3 attempts 401/403/challenge: STOP; no bypass POLICY CHECKS, NOT A PRODUCTION CRAWLER Helpers tested with fake DNS; no real HTTP / scheduler / pinning / robots parser. Address blocks include private, loopback, link-local, metadata, multicast, reserved and org ranges. Caller must implement shared deadlines, waits, budgets, safe XML and controlled evidence retention. Robots compliance is not owner permission. Denials and challenges are findings, not obstacles to bypass. Synthetic v2 policy / helpers are not a complete crawler or an SSRF-safe HTTP client
An automated website audit looks simple from the outside: someone enters a URL, your system fetches the site, and a report comes back covering performance, SEO and security basics. The fetching part is where most of the risk sits. Your servers are sending requests to a site you don't control, often on behalf of someone who typed in a URL. Done carelessly, that can overload a small site, ignore its owner's wishes, or let a user point your servers at your own internal network.
This article sets out a fetch design intended to reduce those risks: what to fetch, what you're allowed to fetch, how fast, what to do when the site pushes back, and when to stop.
About the example. The Flom8 platform I worked on lists Firecrawl API and n8n in its stack for website analysis (case study). Its crawl configuration isn't documented in the case file, so nothing below describes how Flom8 fetches sites. The fetch plan, code and numbers are a synthetic design written for this article. The helper functions shown are partial excerpts of a teaching script. They were unit-tested locally with fake DNS answers and made no network requests (see What was tested). They're policy checks, not a production crawler, scheduler or HTTP client.
This is about how an audit fetches. Whether a business needs an AI-assisted assessment in the first place is a separate question, covered in what to automate first in a small business.
What an audit fetcher actually needs
An audit isn't a search-engine crawl. It needs a representative sample, not the whole site:
| Fetch | Why | Typical cap (synthetic plan) |
|---|---|---|
robots.txt | Rules for your crawler; sitemap locations | 1 per host per run |
| Homepage | Most audit checks start here | 1 |
| Sitemap(s) | Discover important URLs without crawling links | Up to 3 sitemap files, 1 MiB each |
| A capped sample of pages | Templates: a service page, a blog post, a contact page | 10–25 pages |
| Assets, only if a check needs them | e.g. response headers of the main CSS/JS | Headers only, where possible |
A small, fixed budget is kinder to the site, cheaper for you and usually enough to find template-level problems, because most pages on a site share a handful of templates. If a check needs more coverage, raise the cap deliberately for that audit. Don't let the crawler follow links indefinitely.
Scope: permission first, then an allowlist
Robots rules aren't permission. RFC 9309, the Robots Exclusion Protocol, says plainly: "These rules are not a form of access authorization." Honouring robots.txt is a courtesy you owe every site. It isn't consent to audit one. For an audit you run on someone's behalf, get the site owner's permission, and record who gave it and for which domain.
Then turn that permission into an enforced scope:
- Operator-approved origins. An explicit list of scheme, host and port, such as
https://example-client.comandhttps://www.example-client.comon port 443. Subdomains, other ports and plainhttparen't automatically included. Normalise host names one way everywhere (lower case, trailing dot removed, internationalised names converted to theirxn--form) so the same site can't slip past under a different spelling. - Path rules with clear meaning. Separate exact paths from subtrees.
/as an exact path means the homepage only. It doesn't mean "the whole site". A subtree such as/servicescovers/servicesand/services/..., but not/services-admin. Reject paths with dot-segments (/blog/../admin), backslashes, encoded slashes or dots (%2f,%2e), double encoding, or;parameters. Servers and clients disagree about how to normalise those, so refusing them is simpler than matching how the target server will read them. Keep out of account, checkout and admin areas even if they're technically reachable. - Schemes:
httpandhttpsonly. Rejectfile:,ftp:,gopher:and anything else. - No credentials in URLs, and none supplied by the fetcher. An audit of public pages doesn't log in.
Stop the fetcher being turned against your own network
If users can submit URLs, your fetcher is a server-side request service. That's the textbook setup for server-side request forgery (SSRF). OWASP's SSRF Prevention Cheat Sheet is the reference here. Key points it makes:
- Validate the resolved addresses, not just the name. "Domain allowlisting alone does not prevent DNS rebinding. Validate the resolved destination IP addresses against the application's permitted networks, then ensure the HTTP client connects only to validated addresses."
- Re-check redirects. OWASP warns that following redirects can bypass input validation. In an audit you usually need redirects, so validate every hop as if it were a new URL, and drop any hop that leaves the approved scope. Apply the same checks to retries, fallbacks and the
robots.txtand sitemap requests, not just pages. - Block internal ranges. Its minimum deny-list includes cloud metadata at
169.254.169.254, localhost127.0.0.0/8and::1/128, the RFC 1918 private ranges, IPv6 unique-localfc00::/7and IPv6 link-localfe80::/10. IPv4 link-local (169.254.0.0/16) contains the metadata address.
Because your audit scope is an allowlist of approved hosts, you get OWASP's stronger "allowlist" case. The address check is still needed, because an approved name can resolve to an internal address.
A synthetic helper that applies these scope and address rules (tested with fake DNS answers, not live requests):
# SYNTHETIC excerpt of fetch_policy.py (v2), verbatim. Not a crawler or an SSRF-safe HTTP client.
import ipaddress, re, socket
from urllib.parse import urlsplit
DEFAULT_PORTS = {"http": 80, "https": 443}
_ENCODED_SEPARATORS = re.compile(r"%(2e|2f|5c|25)", re.IGNORECASE) # . / \ and double-encoding
class OutOfScope(Exception): pass
DEFAULT_PORTS = {"http": 80, "https": 443}
_ENCODED_SEPARATORS = re.compile(r"%(2e|2f|5c|25)", re.IGNORECASE) # . / \ and double-encoding
def normalize_host(host):
h = (host or "").rstrip(".")
if not h:
raise OutOfScope("missing host")
try:
return h.encode("idna").decode("ascii").lower() # stdlib codec = IDNA 2003; pick one rule and use it everywhere
except UnicodeError:
raise OutOfScope(f"host {host!r} is not a valid IDNA name")
def origin_of(url):
"""(scheme, ascii-host, port) — the unit of scope, robots.txt caching and rate limiting."""
parts = urlsplit(url)
scheme = parts.scheme.lower()
if scheme not in DEFAULT_PORTS:
raise OutOfScope(f"scheme {parts.scheme!r} not allowed")
if parts.username is not None or parts.password is not None:
raise OutOfScope("credentials in URL")
try:
port = parts.port or DEFAULT_PORTS[scheme]
except ValueError:
raise OutOfScope("invalid port")
return scheme, normalize_host(parts.hostname), port
def path_in_scope(path, exact_paths, subtree_roots):
"""Exact paths match only themselves ('/' means the homepage, not the whole site).
Subtree roots match themselves and anything below a segment boundary."""
path = path or "/"
if not path.startswith("/") or "\\" in path or ";" in path or "//" in path:
raise OutOfScope(f"path {path!r} has an ambiguous form")
if _ENCODED_SEPARATORS.search(path) or any(ord(c) < 0x21 or ord(c) > 0x7e for c in path):
raise OutOfScope(f"path {path!r} contains encoded separators or non-ASCII/control characters")
if any(seg in (".", "..") for seg in path.split("/")):
raise OutOfScope(f"path {path!r} contains dot-segments")
if path in exact_paths:
return True
for root in subtree_roots:
root = root.rstrip("/")
if root and (path == root or path.startswith(root + "/")):
return True
raise OutOfScope(f"path {path!r} outside approved paths")
def address_allowed(a, extra_denied=()):
if getattr(a, "ipv4_mapped", None):
a = a.ipv4_mapped
if not a.is_global: # loopback, private, link-local (incl. 169.254.169.254), CGNAT, documentation...
return False
if a.is_multicast or a.is_unspecified or a.is_reserved: # is_global alone is True for e.g. 224.0.0.1, ff0e::1
return False
return not any(a in net for net in extra_denied) # your organisation's own routed ranges
def check_target(url, allowed_origins, exact_paths, subtree_roots, resolve=socket.getaddrinfo, extra_denied=()):
"""Return (origin, [validated IPs]) or raise OutOfScope. Call for the first URL, every redirect hop,
every retry and every robots.txt/sitemap request. Does NOT connect, pin or verify TLS."""
origin = origin_of(url)
if origin not in allowed_origins:
raise OutOfScope(f"origin {origin} not approved by the operator")
path_in_scope(urlsplit(url).path, exact_paths, subtree_roots)
try:
answers = resolve(origin[1], origin[2], proto=socket.IPPROTO_TCP)
except OSError as e:
raise OutOfScope(f"resolution failed: {e}")
ips = {ai[4][0] for ai in answers}
if not ips:
raise OutOfScope("no addresses")
for ip in ips:
if "%" in ip:
raise OutOfScope(f"scoped address {ip}")
if not address_allowed(ipaddress.ip_address(ip), extra_denied):
raise OutOfScope(f"{origin[1]} resolves to disallowed address {ip}")
return origin, sorted(ips) # the client must connect ONLY to these (pinning is not implemented here)Two limits to be honest about:
- The helper returns the validated addresses. Your HTTP client must then connect to those addresses while still sending the original hostname for
Host, TLS SNI and certificate checks. If the client resolves the name again, a rebinding DNS server can answer differently the second time. OWASP describes this pinning. How you do it depends on your HTTP library. The helper doesn't implement pinning, so on its own it isn't an SSRF-safe client. - Python's
ipaddress.is_globalisn't enough by itself. In the test environment (Python 3.13.5) it reported multicast addresses such as224.0.0.1andff0e::1as global, so the helper also rejects multicast, unspecified and reserved addresses explicitly, and unwraps IPv4-mapped IPv6 addresses before checking. Your own organisation may route other ranges internally. Theextra_deniedparameter is where those go. Network-level egress rules are a second layer OWASP recommends alongside application checks.
robots.txt: use RFC 9309 for your own crawler
Search engines document how their crawlers read robots.txt. Google's robots.txt introduction describes it as a file that "tells search engine crawlers which URLs the crawler can access on your site". That documentation describes Googlebot's behaviour. It doesn't define what your audit crawler should do. The shared rule set for a custom crawler is RFC 9309. Points that matter in practice:
| RFC 9309 says | What the fetcher should do |
|---|---|
Crawlers set a product token that "SHOULD be a substring of the identification string" in the User-Agent header, and the string "SHOULD describe the purpose of the crawler" (§2.2.1) | Send an honest User-Agent such as ExampleAuditBot/1.0 (+https://your-site/audit-bot) with a page explaining what it does, and match groups on ExampleAuditBot |
| "The most specific match found MUST be used," meaning the one with the most octets; if Allow and Disallow are equivalent, Allow SHOULD win (§2.2.2) | Use a parser that implements longest match (see the warning below) |
4xx for robots.txt = "unavailable": the crawler "MAY access any resources" (§2.3.1.3) | Our policy is stricter: proceed within scope and caps only for statuses like 404 or 410. 401, 403 and 429 are handled as denial or rate limiting (below) |
| 5xx or network error = "unreachable": the crawler "MUST assume complete disallow" (§2.3.1.4) | Don't audit pages this run; report robots.txt as unreachable. This doesn't enter the normal page retry logic |
| Follow "at least five consecutive redirects" for robots.txt (§2.3.1.2) | Apply your scope and SSRF checks to each hop. The RFC allows following a robots redirect to another host, but here a hop outside the approved origins aborts the audit rather than being followed |
| Don't use a cached copy "for more than 24 hours, unless the robots.txt file is unreachable" (§2.4) | Cache per origin (scheme, host and port) for up to 24 hours |
| "Crawlers SHOULD impose a parsing limit … The parsing limit MUST be at least 500 kibibytes" (§2.5) | Cap the read at, say, 512 KiB and parse what you got |
RFC 9309's security section adds that the protocol "is not a substitute for valid content security measures". That's another reason not to treat a path missing from robots.txt as an invitation.
Where our policy is stricter than the RFC. The RFC's "MAY access" for an unavailable file is permission a crawler can choose not to use. An audit run on someone's behalf should take a refusal at face value, including on the robots.txt request itself:
robots.txt result | Synthetic policy |
|---|---|
| 2xx | Parse with an RFC 9309-conformant parser |
| 404, 410 or other "unavailable" 4xx | Proceed without rules, within scope and caps |
| 401 or 403 | Stop. Fetch no pages and report access denied |
| 429 | Defer. Fetch no pages this run |
| 5xx or network error | Fetch no pages this run and report it as unreachable |
| Redirect outside approved origins, or more than five hops | Abort. Fetch no pages |
The example's robots_outcome function encodes this table and is covered by the tests. It decides what to do with the robots.txt response. It doesn't parse rules.
A parser warning. Python's standard-library urllib.robotparser is convenient but, in a local test for this article, it didn't apply RFC 9309's longest-match rule. Given Disallow: /audit/ followed by Allow: /audit/public/, it reported /audit/public/page as not fetchable. Under longest match, the more specific Allow wins and the page is fetchable. Erring on the side of not fetching is the safe direction, but it isn't the standard behaviour. This was observed in one Python version and may differ in others. Longest match is only part of the job: a parser also has to pick the right user-agent group, handle * wildcards and the $ end marker, and compare paths with the RFC's percent-encoding rules. Don't write your own from the table above. Choose a parser that documents RFC 9309 conformance, and test it against the RFC's examples.
Rate limits, timeouts and budgets
A polite fetcher is a bounded fetcher. Every limit below is a synthetic starting point for small business sites. They aren't figures from any standard or from any real system. Tune them, but make sure every one exists:
Synthetic fetch plan
| Control | Setting | Purpose |
|---|---|---|
| Requests per audit run | 40 max, counting every request: robots.txt, sitemaps, pages (25 max), assets, each redirect hop and each retry | Total request budget |
| Wall-clock budget per run | 3 minutes | Stops a slow site from tying up workers |
| Concurrency per origin | 1 request at a time, coordinated across all audits that target it | Two audits of the same site at once mustn't double the load |
| Delay between requests to an origin | 1 second minimum, shared across concurrent audits | Per-origin rate limit |
| Concurrency across all audits | Capped worker pool | Protects your own infrastructure and outbound IP reputation |
| Connect timeout / read timeout | 5 s / 15 s | Don't hang on unresponsive servers |
| Max bytes per response | 2 MiB for HTML, 1 MiB per sitemap, 512 KiB robots.txt, counted after decompression, with reads stopped at the limit | Stops a huge, endless or compressed-bomb response |
| Redirect hops per URL | 5, each re-validated | Bounded, in-scope redirects |
| Retries per URL | Up to 2 retries (3 attempts total) | Bounded retries |
Parse sitemaps with an XML parser configured safely: no external entities, no DTD processing and limits on entity expansion. A sitemap is untrusted input from someone else's server.
Store what the report needs as evidence: URL, final URL after redirects, status, the headers your checks use, bytes read, whether the body was truncated, and the time. Keep it minimal. Fetched URLs, headers and pages can contain personal data, so redact what the findings don't need, restrict who can read it, and delete it on a set retention schedule. The stored record lets you show the site owner what the audit saw.
None of these limits is implemented in the example helpers. They're design requirements for whatever does the fetching.
When the site pushes back: backoff and hard stops
Google's status-code documentation describes how its own crawlers react: "5xx and 429 server errors prompt Google's crawlers to temporarily slow down with crawling," and "Google's crawlers treat the 429 status code as a signal that the server is overloaded." That's Google's behaviour, not a rule for you, but it's a sensible model.
Retry-After tells you how long to wait. MDN's Retry-After reference says that on a 503 it "indicates how long the service is expected to be unavailable", and on a 429 "how long to wait before making a new request". The value is either a number of seconds or an HTTP date.
The synthetic policy:
| Response | Action | Retry? |
|---|---|---|
429 or 503 with Retry-After that fits the remaining run time | Wait the full stated time, then retry | Yes, within the retry budget |
429 or 503 with Retry-After longer than the remaining run time | Defer: stop requesting from this origin now and report it. Never wait a shorter time and retry early | No, not in this run |
429 or 503 without Retry-After | Exponential backoff: 2 s, then 4 s (add jitter), unless that exceeds the remaining time, in which case defer | Yes, within the retry budget |
Other 5xx | Same as the line above | Yes, within the retry budget |
| Retry budget used up | Record "unreachable" in the report | No |
401 / 403 | Stop. Record "access denied" | No |
| CAPTCHA, bot challenge or interstitial | Stop. Record "challenge served" | No |
| Any other access denial (geo block, WAF block page) | Stop. Record it | No |
And the things this fetcher never does, because each one turns an audit into evasion:
- No proxy or IP rotation to get past rate limits or blocks.
- No
User-Agentspoofing: no pretending to be a browser or a search engine. - No CAPTCHA or challenge solving, whether automated or outsourced.
- No reuse of credentials, cookies or sessions to reach protected areas.
If the site blocks the audit, that's a finding to report to the person who asked for it. The owner can allowlist your crawler's user agent or address if they want the audit to run.
The decision logic is small enough to unit-test. next_action takes a delay that's already been parsed and the time left in the run. It doesn't sleep, add jitter, track a shared deadline or schedule a later run. Those belong to the caller:
# SYNTHETIC excerpt of fetch_policy.py (v2), verbatim. Our policy, not a standard; not a scheduler.
import re
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
def retry_after_seconds(value, now=None):
"""Parse Retry-After (delay-seconds or HTTP-date) into whole seconds, uncapped.
Returns None for absent or invalid values, including dates without a time zone."""
if value is None:
return None
v = value.strip()
if re.fullmatch(r"[0-9]+", v): # ASCII digits only (str.isdigit accepts e.g. '²')
return int(v)
try:
when = parsedate_to_datetime(v)
except (TypeError, ValueError, IndexError, OverflowError):
return None
if when is None or when.tzinfo is None:
return None
now = now or datetime.now(timezone.utc)
if now.tzinfo is None:
raise ValueError("now must be timezone-aware")
return max(0, int((when - now).total_seconds()))
def _number(x, name, allow_none=False):
if x is None and allow_none:
return None
if isinstance(x, bool) or not isinstance(x, (int, float)) or x != x or x < 0:
raise ValueError(f"{name} must be a non-negative number")
return x
def next_action(status, attempt, remaining_budget_s, retry_after=None, max_attempts=3, base=2.0, cap=60.0):
"""Our policy (not a standard) after a page response. retry_after is already-parsed seconds.
Never shortens a requested delay: if it doesn't fit the remaining budget, defer this origin."""
if not (status == "challenge" or (isinstance(status, int) and not isinstance(status, bool) and 100 <= status <= 599)):
raise ValueError("status must be an HTTP status code or 'challenge'")
if isinstance(attempt, bool) or not isinstance(attempt, int) or attempt < 0:
raise ValueError("attempt must be a non-negative integer")
_number(remaining_budget_s, "remaining_budget_s"); _number(retry_after, "retry_after", allow_none=True)
if status in (401, 403) or status == "challenge":
return ("stop", "access denied or bot challenge: record it, do not retry or bypass")
if status == 429 or 500 <= status <= 599:
if attempt + 1 >= max_attempts:
return ("give_up", "retry budget used; report as unreachable")
delay = float(retry_after) if retry_after is not None else min(cap, base * (2 ** attempt))
if delay > remaining_budget_s:
return ("defer", delay) # end this origin's run now; report; any later run is a new, scheduled audit
return ("wait", delay) # jitter and a shared deadline are the caller's job
return ("record", "store status, minimal headers and bytes read for the report")A crawling API or your own fetcher?
You can build the fetcher yourself or use a hosted crawling or scraping API. Firecrawl, which appears in the Flom8 stack, is one example. This article doesn't describe any provider's behaviour. Check each one's own documentation for the specifics. The questions to answer either way are the same:
| Question | Why it matters |
|---|---|
| Can you restrict it to an allowlist of hosts and paths, and cap pages, depth, time and bytes? | Your scope and budget must still be enforced |
How does it treat robots.txt, and can you see that per request? | You remain responsible for honouring the site's rules |
What User-Agent does it send, and from which addresses? | Site owners need to recognise and, if they want, allowlist the audit |
| What does it do on 429/503, 401/403 and bot challenges? | Any proxy rotation, challenge solving or stealth mode conflicts with the "no bypass" rules above |
| Can it reach internal addresses, and whose network does it fetch from? | A hosted fetcher moves the SSRF risk to the provider's network but doesn't remove your scope checks |
| What does it store, for how long, and where? | Fetched pages can contain personal data |
A hosted API can save you building rendering, retries and parsing. Your own fetcher gives you full control and full responsibility. Whichever you choose, keep scope, permission and budgets in your code, before the request leaves your system.
What was tested
The helpers were run locally with Python 3.13.5 against a test script that exits with an error if any check fails. DNS was replaced with a fake resolver, so no network requests were made. 57/57 checks passed, including:
- Scope. The approved HTTPS origin passes, with or without an explicit
:443. The same host on port 8080 or over plainhttp, an unlisted host,file://, credentials in the URL and an invalid port are blocked. A Unicode host name and a trailing-dot host normalise to the approved origin. - Paths. With
/as an exact path,/accountis blocked./servicesand/services/webpass, and/services-admindoesn't. Dot-segments (plain and%2e-encoded),%2f, backslashes,;parameters,//and double encoding are rejected. - Addresses. Metadata
169.254.169.254, a mixed public and private answer,fe80::1, multicast224.0.0.1andff0e::1,0.0.0.0, IPv4-mapped loopback, an organisation-denied range and a DNS failure are all blocked. - Retry-After. Seconds and GMT dates parse.
86400is kept as 86,400 seconds, not shortened. A date with no time zone, garbage and non-ASCII digits return "no value" instead of raising an error. - Next action. 401/403 and challenges stop. A 429 or 503 with a delay that fits is waited in full. A delay beyond the remaining time, whether 86,400 or 600 seconds, or a backoff that doesn't fit, defers. The third attempt gives up. Invalid inputs are rejected.
- robots.txt response policy. Each row of the table above.
- Observation. This Python's
urllib.robotparserdenied the longer-Allow example.
Negative controls: six copies of the helper, each with one safeguard removed, failed the suite. The removed safeguards were the segment-boundary path check, the explicit multicast check, the uncapped Retry-After, defer-instead-of-shorter-wait, robots denial handling and the port check. The original version of the helper also accepted /services-admin, /blog/../admin, /account and port 8080, and turned a 24-hour Retry-After into a 3-minute wait.
Not tested, and not implemented in the helpers: real HTTP fetching, connection pinning to validated addresses, end-to-end redirect handling, request budgets, decompression and read limits, rate limiting across concurrent audits, sitemap parsing, robots rule parsing, evidence storage and any crawling API. Those parts of the plan are design requirements, not tested code. Passing these checks shows the helpers make the stated decisions on these inputs. It doesn't make them a production crawler.
If you want help
If you're building an audit or website-analysis feature into a product and want the fetching side to be safe and well behaved, I can help design and build it as part of automation and AI systems work.
What could this change for you?
Tell me what you’re building — I’ll tell you honestly where I’d start.
Start a project with me