Skip to main content

Test a Shopify redirect map before import

Updated 7 min readMarkdown

A redirect CSV can pass a format check while sending visitors through a loop, pointing to an unpublished product, or asking Shopify to redirect a page that still loads. A useful pre-launch check compares the CSV with a second input, the paths expected to be active when the new store goes live.

The example in this article uses synthetic data. It covers twelve independent scenarios and makes no requests to a store. Ten scenarios produce the expected finding and two control cases pass without findings.

Start with a destination inventory

Export or build a list of the product, collection, page and article paths that will be available at launch. Use paths such as '/products/usb-c-cable' and '/es/products/usb-c-cable'. Keep markets and language prefixes intact. Two URLs can point to equivalent product pages and still need separate rules.

The inventory should reflect publishing decisions. A SKU in a migration export does not establish that its product page will be reachable on the storefront. Draft products, publication settings and renamed handles can all change the result. Ask whoever owns the destination catalog to validate this list before it becomes the input for the redirect audit.

Check the rule and then follow its destination

First, check whether the same source appears with two different targets. A normal spreadsheet filter may catch duplicate cells while missing that one team mapped a discontinued product to a replacement and another mapped it to a collection.

Next, check whether the source itself remains active. Shopify only applies its native URL redirects when the source is broken. Its help documentation also lists reserved or fixed paths, limitations on collection tag URLs, and cases where query strings may behave unexpectedly. See Shopify’s URL redirect documentation.

Finally, follow the destination as a graph. If the destination is also a source, follow its next hop. Keep the paths already visited. Seeing one again identifies a cycle. When the graph reaches a path absent from the inventory, inspect whether it is a typo, a missing publication or an intended destination outside the store. Where the intermediate hop serves no purpose, map the old URL directly to its final destination.

Synthetic example What the check shows
Old cable page to the new product page Direct rule passes
Old Spanish path to its Spanish product page Localized control passes
Old path to an external website Check the external destination separately
A rule under '/cart/' Restricted source
Old path still present in the active inventory Shopify may keep serving the old page
New product path missing from the inventory Verify publication and handle
Old path with a query string Review on the live store
'/old.html' to '/old' Review Shopify’s equivalent-path rule
One old path with two different targets Resolve the conflicting decision
Old cable to intermediate path to product An extra hop
Two old pages pointing to each other Cycle
One path pointing to itself Self redirect

What to verify after launch

Run a fresh browser session or an HTTP client that lets you inspect redirects without relying on your previous cache. Sample URLs with organic traffic and inbound links first. Verify the redirect status, the final response, the canonical and whether the landing page still meets the original visitor’s intent. Include market and language paths as separate checks.

The offline audit cannot establish whether the inventory is accurate, whether Shopify imported the rule as intended, or whether a destination is canonical or equivalent for a shopper. It makes the handover easier by showing the specific rule and destination the team needs to inspect.

For a related example of how catalog and order data were handled alongside a real replatform, see the TiendaCables migration case study. The twelve redirect scenarios above were created separately and do not describe that merchant’s results.

The runnable Python audit is included in 'redirect_audit.py'. Run 'python3 redirect_audit.py --demo' for the twelve assertions. To check your own plan, run 'python3 redirect_audit.py redirects.csv active-paths.txt'. The CSV uses the headers 'Redirect from' and 'Redirect to'. The inventory contains one local path per line.

Runnable example

"""Offline checks for a Shopify redirect plan. Demo data is synthetic."""

import argparse
import csv
import json
from collections import defaultdict
from pathlib import Path
from urllib.parse import urlsplit


RESTRICTED_ROOTS = {
    "apps", "application", "cart", "carts", "orders", "services", "shop",
}
FIXED_PATHS = {"/products", "/collections", "/collections/all"}


def local_path(value):
    if not value.startswith("/") or value.startswith("//"):
        return None
    try:
        return urlsplit(value).path
    except ValueError:
        return None


def audit(rows, active_paths):
    destinations = defaultdict(set)
    origins = set()
    findings = []

    def report(line, source, kind, detail=""):
        findings.append({"line": line, "source": source, "kind": kind, "detail": detail})

    for line, (source, target) in enumerate(rows, start=2):
        source, target = source.strip(), target.strip()
        source_path = local_path(source)
        if not source_path or not target or source.startswith("/\\"):
            report(line, source, "INVALID_ROW", target)
            continue
        if "?" in source or "#" in source:
            report(line, source, "ORIGIN_PARAMETERS", target)
            continue
        origins.add(source_path)
        destinations[source_path].add(target)

    for source, targets in destinations.items():
        if len(targets) > 1:
            report(None, source, "CONFLICTING_TARGETS", ", ".join(sorted(targets)))

    for line, (source, target) in enumerate(rows, start=2):
        source, target = source.strip(), target.strip()
        if source not in origins or not target:
            continue
        if source in FIXED_PATHS or source.split("/")[1] in RESTRICTED_ROOTS:
            report(line, source, "RESTRICTED_ORIGIN", target)
        if source in active_paths:
            report(line, source, "ORIGIN_STILL_ACTIVE", target)
        if len(destinations[source]) > 1:
            continue
        path = local_path(target)
        if not path:
            try:
                external = urlsplit(target)
            except ValueError:
                external = None
            if external and external.scheme in {"http", "https"} and external.netloc:
                report(line, source, "EXTERNAL_TARGET_REVIEW", target)
            else:
                report(line, source, "INVALID_TARGET", target)
            continue
        if source == path:
            report(line, source, "SELF_REDIRECT", target)
            continue
        if source == f"{path}.html":
            report(line, source, "HTML_EQUIVALENT_REVIEW", target)
            continue

        seen = {source}
        chain = [source, path]
        while path in destinations and len(destinations[path]) == 1:
            if path in seen:
                report(line, source, "CYCLE", " -> ".join(chain))
                break
            seen.add(path)
            next_target = next(iter(destinations[path]))
            path = local_path(next_target)
            chain.append(path or next_target)
            if not path:
                report(line, source, "CHAIN_TO_NONLOCAL_TARGET", " -> ".join(chain))
                break
        else:
            if path in destinations:
                report(line, source, "CHAIN_TO_CONFLICT", " -> ".join(chain))
            elif path not in active_paths:
                report(line, source, "DESTINATION_NOT_IN_INVENTORY", " -> ".join(chain))
            elif len(chain) > 2:
                report(line, source, "REDIRECT_CHAIN", " -> ".join(chain))

    return findings


def demo():
    product = "/products/usb-c-cable"
    cases = [
        ("Direct product redirect", [("/old-cable", product)], {product}, set()),
        ("Independent localized path", [("/es/viejo", "/es/products/cable")],
         {"/es/products/cable"}, set()),
        ("External destination", [("/old", "https://example.org/new")], set(),
         {"EXTERNAL_TARGET_REVIEW"}),
        ("Restricted source", [("/cart/old", product)], {product}, {"RESTRICTED_ORIGIN"}),
        ("Source still active", [("/old", product)], {"/old", product}, {"ORIGIN_STILL_ACTIVE"}),
        ("Missing final destination", [("/old", product)], set(),
         {"DESTINATION_NOT_IN_INVENTORY"}),
        ("Query string on source", [("/old?color=black", product)], {product},
         {"ORIGIN_PARAMETERS"}),
        ("Equivalent HTML path", [("/old.html", "/old")], {"/old"}, {"HTML_EQUIVALENT_REVIEW"}),
        ("Conflicting duplicate source", [("/old", product), ("/old", "/products/other")],
         {product, "/products/other"}, {"CONFLICTING_TARGETS"}),
        ("Chain", [("/old", "/interim"), ("/interim", product)], {product}, {"REDIRECT_CHAIN"}),
        ("Cycle", [("/one", "/two"), ("/two", "/one")], set(), {"CYCLE"}),
        ("Self redirect", [("/old", "/old")], set(), {"SELF_REDIRECT"}),
    ]
    results = []
    for name, rows, paths, expected in cases:
        actual = {item["kind"] for item in audit(rows, paths)}
        if actual != expected:
            raise AssertionError(f"{name}: expected {expected}, got {actual}")
        results.append({"case": name, "findings": sorted(actual)})
    return results


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("redirects", type=Path, nargs="?")
    parser.add_argument("active_paths", type=Path, nargs="?")
    parser.add_argument("--demo", action="store_true")
    args = parser.parse_args()
    if args.demo:
        print(json.dumps(demo(), indent=2))
        return
    if not args.redirects or not args.active_paths:
        parser.error("Provide a redirect CSV and a file with one active path per line, or use --demo.")
    with args.redirects.open(encoding="utf-8-sig", newline="") as handle:
        reader = csv.DictReader(handle)
        if not {"Redirect from", "Redirect to"}.issubset(reader.fieldnames or []):
            parser.error("Expected CSV headers: Redirect from, Redirect to")
        rows = [(row.get("Redirect from") or "", row.get("Redirect to") or "") for row in reader]
    paths = {line.strip() for line in args.active_paths.read_text(encoding="utf-8-sig").splitlines()}
    print(json.dumps(audit(rows, paths), indent=2))


if __name__ == "__main__":
    main()

This article and example were prepared with AI assistance. The assertions were run locally against the synthetic fixtures.

About the author

  • Somos Migraciones.io, una agencia Shopify. Trabajamos en diseño y desarrollo de tiendas online, auditorías ecommerce, CRO, migraciones y email marketing con Klaviyo. Compartimos recursos técnicos y criterios para mejorar una tienda Shopify. https://migraciones.io/

No comments yet. Be the first to comment.