# Internal Redirect Chain Watch (`practical_ai_lab_jp/pal-website-internal-redirect-chain-watch`) Actor

Detects multi-hop internal redirect chains on a public HTTPS site and reports when redirect depth grows between scheduled runs.

- **URL**: https://apify.com/practical_ai_lab_jp/pal-website-internal-redirect-chain-watch.md
- **Developed by:** [Practical AI Lab](https://apify.com/practical_ai_lab_jp) (community)
- **Categories:** E-commerce, Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 redirect regression reporteds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Internal Redirect Chain Watch

Finds **multi-hop internal redirect chains** (A → B → C → …) on a public HTTPS website and tells you when the
redirect depth of a URL **grows between runs**. Every finding carries the source URL, where it was found
(sitemap file or page), each hop with its HTTP status, the final URL and a timestamp.

It is a monitoring tool, not a general crawler: it inspects a small, bounded sample of URLs on every run and
compares that sample with the baseline stored from earlier runs.

### Who it is for

- SEO and web teams who release site changes (migrations, URL rewrites, CMS or CDN rules) and want to catch
  redirect chains that quietly get longer.
- Agencies that need a scheduled, evidence-backed check per client domain.

### How it works

1. Validates `startUrl`: public HTTPS site root only. Localhost, IP addresses, internal names, credentials,
   non-default ports, paths and query strings are rejected. The host's DNS answer must be public addresses.
2. Reads `robots.txt` first and obeys it (wildcards, `$`, longest match, `Crawl-delay`). If `robots.txt` is
   unreachable, returns 401/403/5xx, or disallows the start page, the run **fails and nothing else is requested**.
3. Reads sitemaps (from `Sitemap:` lines, otherwise `/sitemap.xml`) with limits on file count, file size (2 MB),
   index nesting and URL count. XML with DTD/entity declarations is rejected.
4. Traces each selected URL **manually**, one redirect at a time. Only same-origin HTTPS hops are followed.
   Cross-origin, non-HTTPS or unsafe redirect targets stop the chain and are never requested.
5. Optionally follows a few same-origin links found on the start page and sitemap pages (one level only).
6. Compares with the per-domain baseline in a key-value store and writes results.

### Input

Only `startUrl` is required. Copy this to try it (replace the domain with a site you are allowed to monitor):

```json
{
    "startUrl": "https://example.com/"
}
```

Optional limits (defaults in brackets): `maxPages` \[40], `maxSitemapUrls` \[300], `maxSitemapFiles` \[5],
`maxLinksPerPage` \[10], `maxRedirectHops` \[5], `minDepthIncrease` \[1], `requestDelayMillis` \[500],
`stateStoreName` \[`pal-redirect-chain-baselines`], `resetBaseline` \[false].

### Output

Results go to the default dataset (JSON/CSV/Excel export from the Apify Console) and, as CSV, to the key-value
store key `REDIRECT_CHANGES_CSV`. The run summary is also stored as `OUTPUT`.

| `status` (in `RUN_SUMMARY`) | Meaning |
| --- | --- |
| `BASELINE_CREATED` | First run for this domain (or `resetBaseline`). Existing multi-hop chains are listed as `BASELINE_CHAIN` records. Never billed. |
| `CHANGES_DETECTED` | At least one `REDIRECT_CHANGE` record. |
| `NO_CHANGES` | Nothing changed in URLs inspected both times. Never billed. |

Change types: `NEW_MULTI_HOP_CHAIN` (2+ internal hops on a URL not inspected before), `DEPTH_INCREASED`
(depth grew by at least `minDepthIncrease` and is now 2+), `DEPTH_DECREASED` (a chain got shorter; informational).

Record shape (placeholder values, for illustration only):

```json
{
    "recordType": "REDIRECT_CHANGE",
    "changeType": "DEPTH_INCREASED",
    "sourceUrl": "https://example.com/old-page",
    "foundOn": "https://example.com/sitemap.xml",
    "discoveredVia": "sitemap",
    "previousDepth": 1,
    "currentDepth": 3,
    "previousChain": ["https://example.com/old-page", "https://example.com/new-page"],
    "currentChain": ["https://example.com/old-page", "https://example.com/step-2", "https://example.com/step-3", "https://example.com/new-page"],
    "hops": [{"url": "https://example.com/old-page", "status": 301, "location": "https://example.com/step-2"}],
    "finalUrl": "https://example.com/new-page",
    "finalStatus": 200,
    "endReason": "final",
    "previousCheckedAt": "2026-01-01T00:00:00+00:00",
    "checkedAt": "2026-01-08T00:00:00+00:00",
    "billable": true
}
```

`endReason` values: `final`, `loop`, `max_hops_reached`, `cross_origin_stopped`, `non_https_stopped`,
`unsafe_location_stopped`, `robots_blocked`, `redirect_without_location`.

### Scheduling

Create an Apify **Schedule** or Task for the same input, for example weekly or after each release. Keep the
default `stateStoreName`: baselines live in a named key-value store, one entry per domain
(`BASELINE_<host>`), so they survive between cloud runs. The run's own default store does not persist on the
platform, so leaving `stateStoreName` empty only makes sense for local runs. Use `resetBaseline` after an
intentional large restructuring to start over.

### Billing event (not configured here)

The code calls `charge()` with the event `redirect-regression-reported`, once per `NEW_MULTI_HOP_CHAIN` or
`DEPTH_INCREASED` record, at most 25 per run. Baseline runs, `NO_CHANGES` runs, improvements, partial page
errors and failed runs emit no event. Events are sent only after results and the new baseline are saved.
This project defines no price and no payable plan; that is decided separately.

### Limitations and sample-size caveats

- **A sample, not an audit.** Only up to `maxPages` URLs (max 200) are traced per run: the start page, the first
  sitemap URLs in document order, then links from those pages. A clean report does not mean the site has no chains.
- **Comparisons need overlap.** A depth change is detected only for a URL inspected in both runs. If the sitemap
  order or links change, a URL may be reported as new even though its chain is old. Treat `NEW_MULTI_HOP_CHAIN`
  as "first seen", not "newly created". The baseline keeps up to 1,500 URLs; the oldest are dropped first and
  entries may be stale (see `previousCheckedAt`).
- **Link discovery is shallow.** Links come only from the start page and sitemap pages; JavaScript-rendered links,
  forms and non-HTML pages are not seen. Gzipped sitemaps (`.gz`) are skipped.
- **Depth is a lower bound** when a chain stops at `max_hops_reached`, at a `robots_blocked` target, or at a
  redirect that leaves the origin or is not HTTPS (those are reported, not followed).
- **Incomplete pages are not compared.** Timeouts, HTTP 429 and 5xx responses make a URL incomplete; it is counted in
  `pagesIncomplete` and excluded from comparison and from the baseline update, so throttling cannot create false
  regressions. If every URL is incomplete the run fails.
- **Single-pass observation.** A redirect rule that varies by user agent, cookie, country or time is seen as the
  crawler saw it once. Intermittent chains can appear and disappear.
- **robots.txt:** the crawler identifies as `PALRedirectChainWatch`. Pages blocked for it are skipped and counted
  in `pagesSkippedByRobots`. Only the host's own robots.txt is considered.
- **DNS rebinding:** the host's address is verified once before requests; the HTTP client then resolves it again.
  Redirects can never leave the origin, which limits exposure, but this is not a pinned-IP guarantee.
- **Not collected:** page text, email addresses, phone numbers, forms or cookies. URLs containing `@` or an
  encoded `@` are skipped so addresses in query strings are not stored.
- No authentication, proxies, headless browser or external services are used. Request pacing defaults to
  500 ms (or the site's `Crawl-delay`, up to 10 s), so a full 200-URL run with long chains can take several minutes.

### Local development

Tests run offline with mocked HTTP (`httpx.MockTransport`) and need `httpx` only:

```
python -m unittest discover -s tests -t .
```

# Actor input Schema

## `startUrl` (type: `string`):

Public HTTPS site root, for example https://example.com/. No path, query string, port, credentials or IP address. robots.txt is read first and obeyed.

## `maxPages` (type: `integer`):

Upper bound on distinct URLs whose redirect chain is traced in one run. The result describes only this sample.

## `maxSitemapUrls` (type: `integer`):

Only the first N same-origin page URLs in sitemap order are considered as candidates.

## `maxSitemapFiles` (type: `integer`):

Limit on sitemap and sitemap index files downloaded (each capped at 2 MB).

## `maxLinksPerPage` (type: `integer`):

Links taken from the start page and sitemap pages (one level only). Use 0 to inspect sitemap URLs only.

## `maxRedirectHops` (type: `integer`):

A chain is cut off after this many internal redirects.

## `minDepthIncrease` (type: `integer`):

A URL is reported as DEPTH_INCREASED when its redirect depth is at least this much higher than in the stored baseline and is now 2 or more.

## `requestDelayMillis` (type: `integer`):

Pause between requests. A larger Crawl-delay in robots.txt takes precedence (capped at 10 seconds).

## `stateStoreName` (type: `string`):

Named key-value store that keeps one baseline per domain between runs. Lowercase letters, digits and hyphens. Leave empty to use the run's default store, which does not persist between cloud runs.

## `resetBaseline` (type: `boolean`):

Discard the stored baseline for this domain and create a new one from this run. Reset runs are never billed.

## Actor input object example

```json
{
  "startUrl": "https://example.com/",
  "maxPages": 40,
  "maxSitemapUrls": 300,
  "maxSitemapFiles": 5,
  "maxLinksPerPage": 10,
  "maxRedirectHops": 5,
  "minDepthIncrease": 1,
  "requestDelayMillis": 500,
  "stateStoreName": "pal-redirect-chain-baselines",
  "resetBaseline": false
}
```

# Actor output Schema

## `results` (type: `string`):

Download rows from the latest run in JSON/CSV.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "startUrl": "https://example.com/"
};

// Run the Actor and wait for it to finish
const run = await client.actor("practical_ai_lab_jp/pal-website-internal-redirect-chain-watch").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "startUrl": "https://example.com/" }

# Run the Actor and wait for it to finish
run = client.actor("practical_ai_lab_jp/pal-website-internal-redirect-chain-watch").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "startUrl": "https://example.com/"
}' |
apify call practical_ai_lab_jp/pal-website-internal-redirect-chain-watch --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,practical_ai_lab_jp/pal-website-internal-redirect-chain-watch"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/fIZrPRl9U418Z4i9R/builds/sGeuVaWKf5JLt9FBU/openapi.json
