Preserve link equity and customer experience when product URLs change, products are removed, or collections are renamed. Automatically handle the most common cases, use analytics data to identify what actually matters, and surface anything ambiguous for admin review.
Product slugs in Berrypod are generated from product titles via `Slug.slugify(title)`. When a provider renames a product, the next sync generates a new slug and the old URL becomes a 404. These old URLs may be:
- Indexed by Google (losing SEO rank)
- Shared on social media, in emails, in newsletters
- Bookmarked by returning customers
Most redirect implementations just provide a manual table. The insight here is that we already have analytics data recording which paths have had real human traffic — so we can separate 404s that matter (broken real URLs) from noise (bot scanners, `/wp-admin` probes, etc.) without any manual work.
When a product's title changes during sync, the slug changes, and the old `/products/old-slug` URL breaks. Detected in `upsert_product/2`.
**Hook point:** `lib/berrypod/products.ex` — the `product ->` branch in `upsert_product/2` where `update_product(product, attrs)` is called. At this point we have `product.slug` (old) and can compute the new slug from `attrs[:title]`.
When a product is removed during sync, create a redirect to the most specific relevant page. Look up the product's category before deletion and redirect to that collection page. If no category is known, fall back to `/`.
Google's guidance is that a 301 to an irrelevant page (soft 404) is worse than a clean 404, so the redirect target must make sense — the collection page shows related products the customer might want.
```elixir
# In delete_product/1, before the actual deletion
category = product.category
target = if category, do: "/collections/#{Slug.slugify(category)}", else: "/"
Redirects.create_auto(%{
from_path: "/products/#{product.slug}",
to_path: target,
source: :auto_product_deleted
})
```
#### 1c. Collection slug change
Categories come from provider tags. If a tag is renamed, the category slug changes and `/collections/old-slug` breaks. Same detection logic — compare old vs new slug in the category upsert path and create a redirect.
Lower priority than products (collection URLs change less often), but the same mechanism handles it.
### Layer 2: A `redirects` table checked early in the Plug pipeline
One table, one Plug, all redirect types flow through the same path.
**Plug position:** Added to the `:browser` pipeline in `router.ex`, before routing. Checks a path, 301s and halts if a redirect exists, otherwise passes through.
1.**Trailing slash normalisation** — `/products/foo/` → `/products/foo`. Phoenix generates no-trailing-slash URLs, so this is the canonical form. Prevents duplicate content in Google's index.
2.**Case normalisation** — `/Products/Foo` → `/products/foo`. URLs are technically case-sensitive per RFC 3986, but mixed-case URLs cause duplicate content issues. Shopify lowercases everything. Only applies to the path, not query params (those can be case-sensitive for variant selectors like `?Color=Sand`).
3.**Redirect table lookup** — custom redirects from the `redirects` table.
All three preserve query params. This matters for variant selection URLs (`?Color=Sand&Size=S`) surviving a product slug change redirect.
**Caching:** The redirect lookup is on the hot path for every request. Use ETS for an in-memory cache, populated on app start and invalidated on any redirect create/update/delete.
```elixir
# On app start, load all redirects into ETS
Redirects.warm_cache()
# On redirect change, invalidate
Redirects.invalidate_cache(from_path)
```
The ETS table maps `from_path` (binary) → `{to_path, status_code}`. Cache miss falls through to DB. Given redirects are rare and mostly set-and-forget, the cache hit rate should be near 100% after warmup.
### Layer 3: Analytics-powered 404 monitoring
When a 404 fires, most hits are bots and scanners. The signal that distinguishes a real broken URL from noise is analytics history: if a path appears in `events` with prior real pageviews, it was a genuine product page.
**404 handler hook:** The existing `error.ex` LiveView renders 404s. Add a side-effect: when a 404 fires on a path matching `/products/:slug` or `/collections/:slug`, query analytics and potentially auto-resolve.
For `/products/:slug` 404s, extract the slug and run it through the FTS5 search index to find the most likely current product:
```elixir
defp attempt_auto_resolve("/products/" <> old_slug, _hits) do
query = String.replace(old_slug, "-", " ")
case Search.search_products(query, limit: 1) do
[%{score: score, slug: new_slug}] when score > @confidence_threshold ->
Redirects.create_auto(%{
from_path: "/products/#{old_slug}",
to_path: "/products/#{new_slug}",
source: :analytics_detected,
confidence: score
})
_ ->
# No confident match - leave in broken_urls for admin review
:ok
end
end
```
The `@confidence_threshold` needs tuning — FTS5 BM25 scores are negative (more negative = better match). Start conservative; it's better to leave something for manual review than to auto-redirect to the wrong product.
For **deleted products** with no match, the redirect target defaults to the product's last known category collection page if that's inferable (from the path or broken_url record), otherwise falls back to `/`.
add :resolved_redirect_id, :binary_id # FK to redirects when resolved
timestamps()
end
create unique_index(:broken_urls, [:path])
create index(:broken_urls, [:status])
create index(:broken_urls, [:prior_analytics_hits]) # sort by impact
```
---
## Admin UI
**Route:** `/admin/redirects`
### Tab 1: Active redirects
Table of all redirects with columns: from path, to path, source (badge: auto/detected/manual), hit count, created at. Delete button to remove. Edit to change destination.
Sources:
-`auto_slug_change` — created automatically when sync detected a slug change. Trust these.
-`analytics_detected` — created from analytics + FTS5 match. Show confidence score. Worth reviewing.
-`admin` — manually created.
### Tab 2: Broken URLs (pending review)
Table sorted by `prior_analytics_hits` descending — highest impact broken URLs at the top.
Columns: path, prior traffic (from analytics), 404s since breaking, first seen.
Each row has a quick action: enter a redirect destination and save, or mark as ignored (e.g. it's a legitimate 404 from a product intentionally removed).
Pre-filled suggestion from FTS5 search (same logic as auto-resolution, just surfaced for human confirmation rather than applied automatically).
### Tab 3: Dead links
See below — dead link monitoring surfaces here alongside redirects, since they're two sides of the same problem.
### Tab 4: Create redirect
Simple form: from path, to path, status code (301/302). For manual one-off redirects (external links, social posts, etc.).
---
## Data flow
```
Provider renames product
↓
ProductSyncWorker → upsert_product/2
↓
old_slug != new_slug detected
↓
Redirects.create_auto({from: /products/old, to: /products/new})
Redirects fix *incoming* broken URLs. Dead link monitoring fixes *outgoing* broken links in your own content — nav links, footer links, social URLs, announcement bar targets, rich text content, product descriptions. Two sides of the same problem.
### Why Berrypod can do this better than external tools
External link checkers (Ahrefs, Screaming Frog, etc.) crawl your site periodically from the outside. They can't know *why* a link broke or *when* it's about to break. Berrypod knows:
- Exactly which URLs are valid (it owns the router and the DB)
- When products are deleted or renamed (sync events)
- Where every admin-configured link is stored (settings keys)
This means internal links can be validated **instantly and without any HTTP request** — just check the router and DB. External links need an async HTTP HEAD check via Oban.
### Sources of links in Berrypod
| Source | Type | When to check |
|--------|------|---------------|
| Nav/footer links (settings) | Internal or external | On save + when referenced product changes |
| Social links (settings) | External | On save + weekly Oban job |
| Announcement bar target URL (settings) | Internal or external | On save |
| Rich text content (future page editor) | Internal or external | On save + when referenced product changes |
| Product descriptions (synced from providers) | Potentially external | After each sync |
| Contact page email | Not a URL | Format validation only |
**Note:** Links rendered *from DB data* (product cards, collection listings) are safe by construction — you only render a link if the product/collection exists. The risk is entirely in user-entered free-text URLs stored in settings or content.
### Two-phase validation
**Phase 1: Internal links — instant router + DB check**
```elixir
defmodule Berrypod.LinkValidator do
alias BerrypodWeb.Router.Helpers
def validate(url) when is_binary(url) do
uri = URI.parse(url)
cond do
# External URL — queue for async check
uri.host != nil -> {:external, url}
# Internal — check router match
true -> validate_internal(uri.path)
end
end
defp validate_internal("/products/" <> slug) do
case Products.get_product_by_slug(slug) do
%{visible: true, status: "active"} -> :ok
%{visible: false} -> {:dead, :product_hidden}
nil -> {:dead, :product_not_found}
end
end
defp validate_internal("/collections/" <> slug) do
if Products.category_exists?(slug), do: :ok, else: {:dead, :category_not_found}
end
defp validate_internal(path) do
# Check against router for known static paths
case Phoenix.Router.route_info(BerrypodWeb.Router, "GET", path, "") do
:error -> {:dead, :no_route}
_match -> :ok
end
end
end
```
**Phase 2: External links — async Oban job**
```elixir
defmodule Berrypod.Workers.ExternalLinkCheckWorker do
use Oban.Worker, queue: :default, max_attempts: 2
def perform(%{args: %{"url" => url, "source_key" => source_key}}) do
case Req.head(url, receive_timeout: 10_000, redirect: true) do
Table of all dead/moved/unchecked stored links, sorted by status (dead first, then moved, then unchecked).
Columns: source (where the link is — "Footer", "Nav", "Announcement bar"), URL, status badge, last checked, action.
Actions:
- **Dead:** "Edit" (opens the relevant settings section pre-focused on that field) — or "Ignore" if intentional
- **Moved:** "Update link" one-click to replace old URL with the new destination in the source setting
- **Unchecked:** "Check now" to trigger immediate validation
Dashboard integration: a small badge on the admin dashboard card ("3 dead links") to draw attention without being annoying. Cleared when all are resolved or ignored.
### Weekly Oban cron job
Re-check all external links stored in `stored_links`. Internal links don't need periodic re-checking — they're validated on demand and on data-change events, which is more efficient.
The weekly job enqueues one `ExternalLinkCheckWorker` job per external stored link, with rate limiting.
### What it deliberately doesn't do
- **Doesn't crawl rendered HTML** — too fragile, too slow. We work from structured data (settings keys, content blocks), not parsed HTML.
- **Doesn't check links in transactional emails** — those are templates, not user content.
- **Doesn't validate email addresses** — format check only, not SMTP validation (too invasive).
- **Doesn't check links in product images** — image URLs are managed by the Media pipeline, not free-text.
### Relationship to redirect system
| Problem | Solution |
|---------|----------|
| Visitor hits a broken URL | **Redirect** — 301 to new location |
| Your own content links to a broken URL | **Dead link fix** — update the link in your content |
| Product renamed — old URL works | Redirect created automatically |
| Product renamed — your nav still says old URL | Dead link flagged as "moved" with suggestion |
They complement each other. The redirect preserves SEO and visitor experience for external links you can't control (social posts, other websites linking to you). The dead link monitor fixes links you *can* control — your own navigation, content, and settings.
Auto-created redirects with zero hits are pruned after 90 days via a weekly Oban cron job. This prevents unbounded growth if products are renamed repeatedly.
```elixir
# Weekly cron: prune stale auto-redirects
from(r in Redirect,
where: r.source in ["auto_slug_change", "auto_product_deleted"] and r.hit_count == 0,
where: r.inserted_at <ago(90,"day")
)
|> Repo.delete_all()
```
Redirects that have been used at least once are kept forever — they're demonstrably serving traffic. Manual (`admin`) and analytics-detected redirects are excluded from auto-pruning; the admin can delete them manually if needed.
**Slug change detection is safe to add with no behaviour change** for products that don't change slug. The `on_conflict: :nothing` insert ensures idempotency across repeated syncs.
**The FTS5 confidence threshold** should be tuned conservatively at first. An incorrect auto-redirect (wrong product) is worse than no redirect. Admin review catches the gaps.
**ETS cache invalidation** needs to happen on: redirect created, updated, deleted. Simple `GenServer` or `:persistent_term` approach — at the scale of a single-tenant shop, the full redirect table easily fits in memory.
**Redirect chains** (A → B → C) should be detected and flattened on creation. If a new redirect's `to_path` is itself an existing `from_path`, follow it and set the new redirect's `to_path` to the final destination. Avoids multi-hop redirects.
**Status code guidance:**
-`301` Permanent — use for slug changes and deleted products. Tells Google to update its index.
-`302` Temporary — only for sales/temporary campaigns. Tells Google to keep the original URL indexed.
---
## Files to create/modify
- Migration — `redirects` and `broken_urls` tables