Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

Two redirect rules stand in for 96 renamed URLs, and the only reason neither one loops is a suffix that is not a suffix

Munchable's site has 461 pages that each answer one question about one ingredient. The slug is the question: /is-onion-low-fodmap, /does-butter-have-lactose, /is-ale-gluten-free. Two conditions got their phrasing wrong

Munchable's site has 461 pages that each answer one question about one ingredient. The slug is the question: /is-onion-low-fodmap, /does-butter-have-lactose, /is-ale-gluten-free.

Two conditions got their phrasing wrong on the first attempt. Lactose pages went out as is-X-high-in-lactose, which is not what people type, and reflux pages as does-X-cause-reflux, where the phrase with the traffic is "acid reflux". By the time I noticed, 96 of those pages were published and some of them were ranking.

So: 96 permanent redirects. Here is all of it.

Patterns, not a list

/**
 * Answer-page slugs that were published and then reworded to the phrase people
 * actually search (lib/content/ingredient-conditions.ts, QUESTION_PHRASING).
 * Permanent, so the ranking the old URLs earned moves with them. Patterns
 * rather than a list, because the ingredient set grows; lib/__tests__ checks
 * that every old slug lands on a page that exists.
 *
 * Neither pattern can match its own destination: "-high-in-lactose" and
 * "-cause-reflux" are not suffixes of "-have-lactose" or "-cause-acid-reflux".
 */
export const LEGACY_QUESTION_REDIRECTS = [
  {
    source: '/is-:ingredient-high-in-lactose',
    destination: '/does-:ingredient-have-lactose',
    permanent: true,
  },
  {
    source: '/does-:ingredient-cause-reflux',
    destination: '/does-:ingredient-cause-acid-reflux',
    permanent: true,
  },
];

That is the whole migration. Two rules, exported from next.config.mjs as a named constant so a test can import them, and handed to Next as redirects: async () => LEGACY_QUESTION_REDIRECTS.

You can watch either one work. munchable.app/is-butter-high-in-lactose answers 308 and points at /does-butter-have-lactose. /does-caffeine-cause-reflux answers 308 and points at /does-caffeine-cause-acid-reflux.

The reason it is patterns and not a generated list of 96 entries is that the ingredient set is not finished. A list would be correct today and silently incomplete the moment another ingredient gets a lactose page, because that new page gets the new phrasing and nobody would think to add an old URL for a page that never had one. Writing the rename as a shape rather than as an enumeration means it covers slugs that do not exist yet, which is a strange thing to want until you remember that old URLs arrive from other people's links, other people's spreadsheets and Google's index, on their schedule rather than yours.

A dynamic segment in a redirect source is "anything"

Here is the part that is worth more than the five lines suggests.

:ingredient in a redirect source is not "a word". It matches any run of characters that is not a slash, and these slugs are full of hyphens, so :ingredient will happily swallow beer-cause-acid if the rest of the pattern lines up. The pattern is really does- plus anything plus -cause-reflux.

Which means the only thing standing between this config and an infinite redirect is whether a destination can match its own source. Work it through for the reflux rule. The destination of /does-beer-cause-reflux is /does-beer-cause-acid-reflux. Does the source pattern match that? It would need the path to end in -cause-reflux. It ends in -acid-reflux. The word "cause" is in there, but it is in the wrong place, so the match fails and the redirect fires exactly once.

The lactose rule is safe twice over: the source needs an is- prefix and its destination starts with does-, and the source needs a -high-in-lactose suffix which -have-lactose is not.

That is the whole safety argument, and it is an argument about string suffixes rather than anything the framework checks for you. It is also easy to lose. Suppose the rewording had gone the other way and the new slug were does-X-really-cause-reflux:

{ source: '/does-:ingredient-cause-reflux',
  destination: '/does-:ingredient-really-cause-reflux' }

That destination still ends in -cause-reflux, so the source matches it with :ingredient bound to beer-really, and it redirects again, with beer-really-really, for ever. Same five lines, same framework, and the difference between the two versions is where one word sits inside a string.

Nothing warns you. Next will serve a 308 to a URL that 308s back, and the browser will show a redirect error on the page that used to rank.

So I wrote the argument down in the comment, and then I stopped trusting the comment.

The test that does not trust the comment

// Next's own copy of path-to-regexp, so the redirect patterns are matched
// exactly as the server matches them. It ships without types.
const { compile, match } = createRequire(import.meta.url)('next/dist/compiled/path-to-regexp') as {
  match: (pattern: string) => (path: string) => false | { params: Record<string, string> };
  compile: (pattern: string) => (params: Record<string, string>) => string;
};

Reaching into next/dist/compiled is reaching into somebody's private implementation, and I would normally refuse. I made an exception here, and I think the reasoning generalises.

The thing being tested is not my code. It is the interaction between my two strings and a matching library whose semantics I am clearly capable of getting wrong, since the entire risk in this file is a subtlety about how greedily a parameter matches. If I write the test against path-to-regexp from my own devDependencies, I am testing my patterns against a version of the matcher that is nearly the same as the one in production. Nearly is exactly the word you do not want in a sentence about redirect loops. Importing the copy Next actually uses means the test and the server agree by construction, and if Next changes that copy, I would rather the test break loudly in CI than have the behaviour change quietly on the live site.

With the matcher in hand, the two tests write themselves. The first replays history:

const LEGACY_SLUG: Partial<Record<string, (ingredient: string) => string>> = {
  lactose: (i) => `is-${i}-high-in-lactose`,
  gerd: (i) => `does-${i}-cause-reflux`,
};

it('sends every old lactose and reflux slug to the page that replaced it', () => {
  for (const ref of ANSWER_PAGES) {
    const legacy = LEGACY_SLUG[ref.condition];
    if (!legacy) continue;
    assert.equal(redirect(`/${legacy(ref.ingredientSlug)}`), `/${ref.question}`);
  }
});

It reconstructs the old URL for every page that ever had one, from the ingredient slug the page is built from, and asserts the rules land it on the page that exists now. 96 assertions out of a seven-line table. Nothing is written down twice, so nothing can be updated in one place and not the other.

The second one is the loop guard, and it is the test I would keep if I could only have one:

it('redirects no page that exists', () => {
  for (const ref of ANSWER_PAGES) {
    assert.equal(redirect(`/${ref.question}`), null, `/${ref.question} would redirect`);
  }
  for (const page of FOOD_LIST_PAGES) {
    assert.equal(redirect(`/${page.slug}`), null, `/${page.slug} would redirect`);
  }
});

Every live URL on the site, run through the redirect table, asserting nothing matches. That is 461 answer pages plus the seven list hubs, and it holds the comment's claim about suffixes to account over the entire URL space rather than over the two examples I happened to think about. It also covers a case the comment does not mention at all: the hubs sit at the site root beside the answer pages, with slugs like /foods-with-lactose, and one of those is a renaming away from being caught by a pattern aimed at something else.

The wart I decided to keep

A pattern cannot know which ingredients have pages. So munchable.app/is-nonsense-high-in-lactose answers a confident 308 to /does-nonsense-have-lactose, which is a 404. Two requests to tell somebody their URL is wrong, where a plain 404 would have taken one.

I thought about guarding it, and the guard is worse. It would mean either generating 96 exact redirects after all, which gives up the coverage of slugs that do not exist yet, or moving the decision into a proxy that can see the page registry, which puts a runtime lookup in front of a site that is otherwise entirely static. For a URL shape that only a typo or a broken scraper produces, a 308 into a 404 is the right trade. It is also honest: the old shape genuinely did map to that new shape, and the new page genuinely does not exist.

What I would not accept is the same wart on a URL somebody actually has. The difference between those two cases is the first test above, which is why it reconstructs the old URLs from real ingredients instead of from a list I typed.

If you want to see where any of this lands, the index of all 461 is at munchable.app/answers, and the reflux ones gather on /acid-reflux-foods-to-avoid with the phrasing I should have used in the first place.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.