Shopify: Create redirects for all product handles

Created by Todd Belcher, Modified on Wed, 23 Oct, 2024 at 2:12 PM by Todd Belcher

We needed to create a redirect for every product in Shopify while uninstalling an AMP app


The app had created duplicates of every page with /a/s appended to the front end of the URL, which were triggering duplicate errors and warnings in Semrush. We also found that these URLs were capable of search cannibalization, and the app did not handle its exit gracefully. Every AMP URL from before was now a 404 error.


We downloaded an export of all products, and the Shopify redirect template


Redirect from,Redirect to
/example_product.php,/products/example-product


That's the Shopify redirect template. Simple enough! We didn't have DNS or server access to set up rewrites or redirects, so utilizing Shopify's built-in redirect tool worked well.


We were able to set up hundreds and hundreds of redirects in just a few minutes. Here's the Python code we used to put together the import for upload: 


import pandas as pd
from datetime import datetime

# Load the inventory CSV (with error handling)
inventory_file = "products_export_1.csv"
try:
    # Only load the 'Handle' column to optimize memory usage
    inventory_data = pd.read_csv(inventory_file, usecols=["Handle"])
except ValueError as e:
    print(f"Error loading 'Handle' column: {e}")
    exit(1)

# Drop any rows with missing 'Handle' values
inventory_data.dropna(subset=["Handle"], inplace=True)

# Extract the 'Handle' column as a list
handles = inventory_data["Handle"].tolist()

# Create a new DataFrame for the redirects
redirects = pd.DataFrame({
    "Redirect from": [f"/a/s/products/{handle}" for handle in handles],
    "Redirect to": [f"/products/{handle}" for handle in handles]
})

# Create the output filename with the current date
output_filename = f"shopify_redirects_{datetime.now().strftime('%Y%m%d')}.csv"

# Save the new CSV file
redirects.to_csv(output_filename, index=False)

print(f"Redirects file created: {output_filename}")

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article