DEV Community

Sushil Barwal
Sushil Barwal

Posted on Fully Autonomous

Building a WooCommerce to Shopify redirect map with a small Python script

When a store moves from WooCommerce to Shopify, the products and customers are the easy part. The part that decides whether the store keeps its Google traffic is the redirect list: one permanent redirect from every old WooCommerce URL to its new Shopify address, live on launch day.

Shopify doesn't let you keep WooCommerce's URL shapes. Products always live under /products/, collections under /collections/, pages under /pages/ and blog posts under /blogs/<blog-name>/. So on a typical store almost every URL changes. Doing that by hand for a few hundred products is slow and error-prone, so here's the small script we use as a starting point.

What the mapping looks like

These are WooCommerce's default bases. Check yours under Settings > Permalinks in WordPress first, because many stores change them.

WooCommerce URL Shopify URL
/product/blue-hoodie/ /products/blue-hoodie
/product-category/hoodies/ /collections/hoodies
/product-category/clothing/hoodies/ /collections/hoodies
/product-tag/sale/ /collections/sale (if you build it)
/2024/05/how-to-wash-wool/ /blogs/news/how-to-wash-wool
/about-us/ /pages/about-us

Two things to note. Shopify has no nested collections in the URL, so a deep category path becomes one flat collection. And Shopify's default blog is called "News", which is why posts land under /blogs/news/.

Step 1: collect every old URL

Don't build the list from the product export alone. You want every URL that has ever earned traffic or links. Combine three sources:

  1. The WordPress sitemaps (/wp-sitemap.xml on recent WordPress, or your SEO plugin's sitemap index).
  2. A Search Console Pages export for the last 12 months, so you catch old URLs that still get clicks.
  3. Your backlink tool's "top pages" export, if you have one.

Put them all in one text file, one URL per line. Duplicates are fine; the script removes them.

Step 2: map them with a script

import csv
import re
import sys
from urllib.parse import urlparse

PRODUCT_BASE = "product"            # Settings > Permalinks > Product base
CATEGORY_BASE = "product-category"
TAG_BASE = "product-tag"
BLOG_HANDLE = "news"                # Shopify's default blog

DATE_POST = re.compile(r"^/\d{4}/\d{2}(/\d{2})?/([^/]+)/?$")

def map_path(path: str):
    """Return (new_path, rule) or (None, reason)."""
    parts = [p for p in path.strip("/").split("/") if p]
    if not parts:
        return None, "homepage: no redirect needed"
    if parts[0] == PRODUCT_BASE and len(parts) >= 2:
        return f"/products/{parts[-1]}", "product"
    if parts[0] == CATEGORY_BASE and len(parts) >= 2:
        return f"/collections/{parts[-1]}", "category (flattened)"
    if parts[0] == TAG_BASE and len(parts) >= 2:
        return f"/collections/{parts[-1]}", "tag -> check collection exists"
    if parts[0] in ("shop", "cart", "checkout", "my-account"):
        return None, "reserved on Shopify: link to /collections/all instead"
    m = DATE_POST.match(path)
    if m:
        return f"/blogs/{BLOG_HANDLE}/{m.group(2)}", "dated post"
    if len(parts) == 1:
        return f"/pages/{parts[0]}", "page or undated post -> check"
    return None, "unmatched: map by hand"

def main(infile: str, outfile: str, review: str):
    seen = set()
    with open(infile) as f, open(outfile, "w", newline="") as out, \
         open(review, "w", newline="") as rev:
        ok = csv.writer(out)
        todo = csv.writer(rev)
        ok.writerow(["Redirect from", "Redirect to"])
        todo.writerow(["Old URL", "Suggested", "Reason"])
        for line in f:
            url = line.strip()
            if not url:
                continue
            path = urlparse(url).path or "/"
            if path in seen:
                continue
            seen.add(path)
            new, rule = map_path(path)
            if new and "check" not in rule:
                ok.writerow([path, new])
            else:
                todo.writerow([path, new or "", rule])

if __name__ == "__main__":
    main(*sys.argv[1:4])
Enter fullscreen mode Exit fullscreen mode

Run it with python3 woo_redirects.py old-urls.txt redirects.csv review.csv.

redirects.csv uses the two columns of Shopify's sample template (Redirect from, Redirect to), so it can go straight into the bulk import. Everything the script isn't sure about goes into review.csv for a person to decide.

Step 3: fix the cases a script can't decide

The review file usually holds four kinds of rows:

  • Tags. A WooCommerce tag archive only has a home on Shopify if you build a matching collection. If you don't, point it at the closest collection rather than the homepage.
  • Single-segment URLs. /about-us/ might be a page, but on a store using "Post name" permalinks it could be a blog post. Check them against the WordPress export.
  • /shop/. Shopify reserves paths starting with /shop, /cart and /apps, so you can't redirect them. Link to /collections/all from the navigation instead.
  • Changed slugs. If you renamed a product during the move, the script's guess will 404. Keep slugs the same wherever you can; it makes this whole step much shorter.

Step 4: import, then test before the DNS switch

Shopify keeps redirects under Content > Menus > URL redirects, with a CSV import. Three rules from Shopify's help docs catch people out:

  1. A redirect only fires if the old URL is broken. If a page with that address exists on Shopify, the redirect is ignored.
  2. A standard store holds up to 100,000 redirects, which is plenty for most migrations.
  3. Reserved paths (above) can't be redirected at all.

Before you point the domain at Shopify, test the list against the new store's preview domain with a quick loop that requests each "Redirect from" path and checks it returns a 301 to the right target. After launch, run it again against the live domain and watch Search Console's Pages report for new 404s over the next few weeks.

FAQ

Can I just redirect everything to the homepage?
No. Google treats mass redirects to the homepage much like 404s, so the old pages' ranking signals are lost. Map each URL to its closest equivalent.

What about query strings like ?add-to-cart=123?
Leave them out. They aren't indexed pages, and Shopify matches redirects on the path.

Do customer passwords move?
No, on any platform. With Shopify's current customer accounts, people sign in with their email and a one-time code, so tell customers before launch.

How long should I keep the WooCommerce site?
Keep it online until the product import is finished, because Shopify downloads images from the URLs in your CSV.

If you'd rather hand the whole move to a team that does this every week, Dzimark runs WooCommerce, Magento and BigCommerce migrations to Shopify for stores in the USA, UK, Canada and Australia.

Top comments (0)