# URL Canonicalizer (`junipr/url-canonicalizer`) Actor

Canonicalize URLs by stripping tracking parameters, normalizing hosts, paths, query strings, and grouping equivalent URL variants.

- **URL**: https://apify.com/junipr/url-canonicalizer.md
- **Developed by:** [junipr](https://apify.com/junipr) (community)
- **Categories:** SEO tools, Developer tools, E-commerce
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.95 / 1,000 url normalizeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## URL Canonicalizer

### Store Positioning

**Store title:** URL Canonicalizer

**Short description:** Canonicalize URLs by stripping tracking parameters, normalizing hosts, paths, query strings, and grouping equivalent URL variants.

**SEO title:** URL Canonicalizer — fast deterministic data utility

**SEO description:** Canonicalize URLs by stripping tracking parameters, normalizing hosts, paths, query strings, and grouping equivalent URL variants. Use it for fast, low-cost normalization or validation at scale with predictable pay-per-event pricing.

**Categories:** SEO\_TOOLS, DEVELOPER\_TOOLS, ECOMMERCE

**Keywords:** url, canonicalizer, tiny deterministic utility

### Pay-Per-Event Pricing

This actor uses pay-per-event pricing. Event prices include Apify platform usage; users are not expected to pay a separate platform-usage pass-through charge for the configured pricing model.

- Primary event: `url-normalized` at $0.00195 base

Event set:

- `actor-start`: $0.00176 when run setup is accepted.
- `url-normalized`: $0.00195 for each valid URL emitted to the dataset.
- `report-generated`: $0.02000 when CSV, JSON, summary, and Markdown files are created.

### Public Task Concepts

- Normalize URL Canonicalizer records
- Validate URL Canonicalizer values in bulk
- Generate a small utility report for URL Canonicalizer
- Group equivalent campaign URL variants
- Export a canonical URL migration map

Canonicalize URLs by stripping tracking parameters, normalizing variants, and grouping equivalent URLs before using them in crawl inputs, redirects, analytics, SEO QA, lead exports, or client reports.

### What This Actor Does

Url Canonicalizer accepts URL lists, row objects, and mixed text, then produces deterministic canonical URLs:

- Adds `https://` to schemaless URLs when enabled.
- Forces HTTPS by default.
- Lowercases hostnames and removes leading `www`.
- Removes fragments, index files, trailing slashes, empty query parameters, and common tracking parameters.
- Sorts kept query parameters for stable dedupe keys.
- Groups equivalent URL variants and marks duplicates.
- Writes canonical URL CSV, group JSON, and Markdown/JSON reports.

### What This Actor Does Not Do

- It does not crawl pages or verify HTTP status codes.
- It does not fetch canonical tags from live pages.
- It does not create redirects or modify websites.
- It does not guarantee legal, privacy, or SEO compliance.

### Best Use Cases

- Clean crawl input lists before SEO audits.
- Deduplicate campaign URLs that differ only by UTM parameters.
- Normalize URL exports before redirect migrations.
- Extract URLs from notes or row fields and produce clean import keys.
- Prepare client reports with grouped URL variants.

### Input Fields

- `urls`: URL or URL-like strings to canonicalize.
- `records`: Optional objects containing URL fields or text fields.
- `urlFields`: Fields read as direct URLs from `records`.
- `textFields`: Fields scanned for URLs when text extraction is enabled.
- `mixedText`: Free text to scan for URLs.
- `extractUrlsFromText`: Enables URL extraction from text fields and mixed text.
- `allowSchemalessUrls`: Treats strings like `example.com/path` as HTTPS URLs.
- `forceHttps`, `stripWww`, `stripHash`, `stripTrailingSlash`, `stripIndexFiles`: Canonicalization controls.
- `stripParams`: Query parameter names to remove.
- `keepParams`: Query parameter names to preserve even if they normally match strip rules.
- `includeInvalid`: Include invalid URL inputs in the dataset with errors.
- `maxItems`: Maximum extracted URL items to process. Default is 100 and hard cap is 50,000.
- `includeReport`: Store canonical CSV, group JSON, and summary reports.

### Example Input

```json
{
  "urls": [
    "https://www.Example.com/products/widget/?utm_source=newsletter&utm_medium=email&ref=abc#reviews",
    "http://example.com/products/widget?ref=abc&utm_campaign=spring",
    "example.com/products/widget/?ref=abc"
  ],
  "maxItems": 100,
  "includeReport": true
}
```

### Output Fields

Each dataset item represents one input or extracted URL:

- `itemId`: Stable identifier for the processed URL item.
- `sourceType`, `sourceId`, `recordIndex`, `fieldName`: Source metadata.
- `originalValue`: Original URL-like value.
- `status`: `canonicalized`, `unchanged`, `duplicate`, or `invalid`.
- `canonicalUrl`: Normalized URL when valid.
- `normalizedHost`, `rootDomain`, `normalizedPath`: Normalized URL parts.
- `queryParamsKept` and `queryParamsRemoved`: Query parameter audit trail.
- `changed` and `changeReasons`: Whether and why the URL changed.
- `groupKey`, `groupSize`, `duplicateOfItemId`: Equivalent URL grouping.
- `issues`: Structured validation issues.
- `recommendation`: Short next step.

The key-value store also contains:

- `CANONICAL_URLS.csv`: Canonical URL rows for import or reporting.
- `CANONICAL_GROUPS.json`: Grouped canonical URLs and variants.
- `URL_CANONICALIZER_REPORT.md`: Human-readable summary report.
- `URL_CANONICALIZER_SUMMARY.json`: Machine-readable summary.

### Example Output

```json
{
  "originalValue": "https://www.Example.com/products/widget/?utm_source=newsletter&utm_medium=email&ref=abc#reviews",
  "status": "canonicalized",
  "canonicalUrl": "https://example.com/products/widget?ref=abc",
  "queryParamsRemoved": ["utm_source", "utm_medium"],
  "groupSize": 3,
  "duplicateOfItemId": null,
  "recommendation": "Use the canonical URL for dedupe keys, redirects, crawl inputs, or reporting."
}
```

### Cost-Control Tips

- Start with the default input or `maxItems` between 25 and 100.
- Verify `stripParams` and `keepParams` on a small batch before processing a large export.
- Keep `includeInvalid` on for QA workflows so bad URLs are visible.
- Keep `includeReport` on for normal runs so canonical CSV and group JSON artifacts are generated.

### Public Task Examples

This actor includes prepared task concepts:

- Canonicalize campaign URLs.
- SEO crawl URL cleanup.
- Extract URLs from notes.
- Canonicalize row fields.

### FAQ

#### Does this fetch pages and read canonical tags?

No. This is a deterministic URL string canonicalizer. It intentionally avoids network access so runs stay fast, predictable, and cheap.

#### Can I preserve a UTM parameter?

Yes. Add that parameter name to `keepParams`.

#### Does this use a full public suffix database?

No. Root domain is a best-effort convenience field. The primary grouping key is the canonical URL.

### Troubleshooting

- URL was invalid: check whether it has spaces, missing host parts, or an unsupported scheme.
- Important query parameter was removed: add it to `keepParams`.
- URLs did not group together: compare kept query parameters and paths in the output.
- Too many inputs: lower `maxItems` and validate a smaller batch first.

### Limitations

- No live HTTP checks, redirect following, canonical tag extraction, or sitemap crawling.
- Best-effort root-domain extraction only.
- URL extraction from text is intentionally conservative and may miss unusual formats.

### Source And Safety Notes

This actor processes user-provided URL strings and row objects. Do not upload confidential URLs unless you are authorized to process them in Apify.

### Changelog

- `1.0.0`: Initial production build with URL parsing, canonicalization, equivalent grouping, clean CSV/group artifacts, report generation, PPE billing, examples, and fixture tests.

# Actor input Schema

## `urls` (type: `array`):

URLs or URL-like strings to canonicalize.

## `records` (type: `array`):

Optional row objects that contain URL fields or text fields.

## `urlFields` (type: `array`):

Record fields that should be read as direct URLs.

## `textFields` (type: `array`):

Record fields to scan for URLs when extractUrlsFromText is enabled.

## `mixedText` (type: `string`):

Optional free text containing URLs to extract and canonicalize.

## `extractUrlsFromText` (type: `boolean`):

Extract URL-like strings from mixedText and configured text fields.

## `allowSchemalessUrls` (type: `boolean`):

Treat strings like example.com/path as HTTPS URLs.

## `forceHttps` (type: `boolean`):

Convert http:// URLs to https:// in canonical output.

## `stripWww` (type: `boolean`):

Remove leading www. from hostnames.

## `stripHash` (type: `boolean`):

Remove URL fragments.

## `stripTrailingSlash` (type: `boolean`):

Remove trailing slash from non-root paths.

## `stripIndexFiles` (type: `boolean`):

Normalize /index.html and similar index files to the containing path.

## `sortQueryParams` (type: `boolean`):

Sort kept query parameters by name and value.

## `dropEmptyQueryParams` (type: `boolean`):

Drop query parameters with empty values.

## `stripParams` (type: `array`):

Query parameters to remove. Defaults include common tracking parameters.

## `keepParams` (type: `array`):

Important parameters to preserve even if they look like tracking parameters.

## `includeInvalid` (type: `boolean`):

Include invalid URL inputs in the dataset with issues.

## `includeReport` (type: `boolean`):

Write canonical URL CSV, group JSON, and report artifacts to the key-value store.

## `maxItems` (type: `integer`):

Maximum extracted URL items to process. Default is small and safe for Apify quality checks.

## `dryRun` (type: `boolean`):

Validate input and write a dry-run summary without PPE charges or dataset output.

## `debug` (type: `boolean`):

Enable debug-level logs.

## Actor input object example

```json
{
  "urls": [
    "https://www.Example.com/products/widget/?utm_source=newsletter&utm_medium=email&ref=abc#reviews",
    "http://example.com/products/widget?ref=abc&utm_campaign=spring",
    "example.com/products/widget/?ref=abc"
  ],
  "urlFields": [
    "url",
    "sourceUrl",
    "landingPage"
  ],
  "textFields": [
    "text",
    "description",
    "notes"
  ],
  "extractUrlsFromText": true,
  "allowSchemalessUrls": true,
  "forceHttps": true,
  "stripWww": true,
  "stripHash": true,
  "stripTrailingSlash": true,
  "stripIndexFiles": true,
  "sortQueryParams": true,
  "dropEmptyQueryParams": true,
  "stripParams": [
    "utm_source",
    "utm_medium",
    "utm_campaign",
    "utm_term",
    "utm_content",
    "fbclid",
    "gclid",
    "msclkid"
  ],
  "keepParams": [],
  "includeInvalid": true,
  "includeReport": true,
  "maxItems": 100,
  "dryRun": false,
  "debug": false
}
```

# Actor output Schema

## `dataset` (type: `string`):

Structured URL normalization and duplicate-group rows.

## `summary` (type: `string`):

Run summary artifact stored in the default key-value store.

# 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 = {
    "urls": [
        "https://www.Example.com/products/widget/?utm_source=newsletter&utm_medium=email&ref=abc#reviews",
        "http://example.com/products/widget?ref=abc&utm_campaign=spring",
        "example.com/products/widget/?ref=abc"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("junipr/url-canonicalizer").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 = { "urls": [
        "https://www.Example.com/products/widget/?utm_source=newsletter&utm_medium=email&ref=abc#reviews",
        "http://example.com/products/widget?ref=abc&utm_campaign=spring",
        "example.com/products/widget/?ref=abc",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("junipr/url-canonicalizer").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 '{
  "urls": [
    "https://www.Example.com/products/widget/?utm_source=newsletter&utm_medium=email&ref=abc#reviews",
    "http://example.com/products/widget?ref=abc&utm_campaign=spring",
    "example.com/products/widget/?ref=abc"
  ]
}' |
apify call junipr/url-canonicalizer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,junipr/url-canonicalizer"
        }
    }
}
```

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/1kr06aBL50RpkfX3V/builds/SRomf7GMG3CW3zg7w/openapi.json
