8.10 — Catch-All Routes, Slugs and SEO-Friendly URLs¶
← Roadmap · Section: 8. Routing Prev: 8.9 Route groups · Next: 9.1 The MVC pattern
Markers: — · Confidence: 🔴 · Last reviewed: —
TL;DR¶
A slug is the human-readable part of a URL — blue-widget in /products/blue-widget. A
catch-all route captures everything remaining in a path, slashes included.
- Slugs need to be stable and unique, so most sites use an ID plus slug —
/products/42/blue-widget. - Catch-alls suit hierarchical paths — nested categories, file trees, CMS pages.
- ⚠️ A catch-all captures
../, so never build a file path from one.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Slug | a URL-safe text identifier | blue-widget. Derived from a title, lowercase, hyphenated. |
| Catch-all | {*rest} or {**rest} |
Captures the remaining path including slashes. |
| Round-trip catch-all | {**rest} |
Does not re-encode slashes when generating links. See 8.6. |
| Canonical URL | the one true URL | The single address a page should be reached at. Others redirect to it. |
| 301 / 308 | permanent redirects | Tell clients and search engines the URL moved for good. |
| Slugify | a transformation | Turning a title into a slug — lowercase, strip punctuation, hyphenate. |
| Path traversal | an attack | Using ../ to escape a directory. Catch-alls capture it happily. |
{*path:nonfile} |
a constraint | Excludes paths that look like files. Used with SPA fallbacks. |
The concept¶
Why slugs exist¶
Compare:
The second is better for three reasons. People can read it and guess what it points at. Search engines weight words in URLs, so a descriptive path helps ranking. And it survives being pasted into a chat message without looking like a mistake.
The cost is that slugs are derived from titles, and titles change. That creates the problem this note is really about: what happens when the slug changes?
A picture: a street address versus grid coordinates. "10 Downing Street" is memorable and meaningful. Coordinates never change but tell you nothing. Most systems want both — the address for humans, the coordinates for certainty.
⚠️ The stability problem¶
[HttpGet("products/{slug}")]
public async Task<IActionResult> Get(string slug, CancellationToken ct) { }
That looks clean and has three problems:
Slugs change. Rename "Blue Widget" to "Azure Widget" and every existing link breaks — including external ones you do not control and search engine results you cannot edit.
Slugs collide. Two products called "Blue Widget" produce the same slug, so you need a uniqueness constraint and a disambiguation strategy.
Lookup by slug needs an index. Querying a text column instead of a primary key is slower and needs a deliberate database index.
The common answer is ID plus slug:
The ID does the lookup; the slug is decoration. Change the title and the old URL still works — you just redirect it to the new one. That is the pattern Stack Overflow, GitHub and most large sites use.
How it works¶
The simple version — ID plus slug¶
[HttpGet("products/{id:int}/{slug?}")]
public async Task<IActionResult> Get(int id, string? slug, CancellationToken ct)
{
var product = await _products.GetAsync(id, ct);
if (product is null) return NotFound();
// If the slug is missing or stale, redirect to the canonical URL
if (!string.Equals(slug, product.Slug, StringComparison.Ordinal))
return RedirectToActionPermanent(nameof(Get), new { id, slug = product.Slug });
return View(product);
}
Three things that does:
/products/42 works — the slug is optional, so a bare ID redirects to the full URL.
A stale slug still works — /products/42/old-name redirects to the current name rather than
404ing.
One canonical URL — search engines see a single address per product rather than several, which avoids splitting ranking across duplicates.
⚠️ RedirectToActionPermanent issues a 301, which browsers and search engines cache
aggressively. That is what you want for a genuinely permanent move — and it means a mistake is
hard to undo, because clients keep following the cached redirect. Use a temporary 302 while you
are still deciding.
Generating a slug¶
public static string Slugify(string title)
{
if (string.IsNullOrWhiteSpace(title)) return string.Empty;
// Decompose accented characters so "café" becomes "cafe" rather than being stripped
var normalized = title.Normalize(NormalizationForm.FormD);
var builder = new StringBuilder(normalized.Length);
foreach (var ch in normalized)
{
var category = CharUnicodeInfo.GetUnicodeCategory(ch);
if (category == UnicodeCategory.NonSpacingMark) continue; // drop the accent mark
if (char.IsLetterOrDigit(ch))
builder.Append(char.ToLowerInvariant(ch));
else if (ch is ' ' or '-' or '_')
builder.Append('-');
}
// Collapse runs of hyphens and trim the ends
var slug = Regex.Replace(builder.ToString(), "-{2,}", "-").Trim('-');
return slug.Length > 80 ? slug[..80].TrimEnd('-') : slug;
}
⚠️ ToLowerInvariant, not ToLower. Culture-sensitive lowercasing produces different results
on different machines — the Turkish dotless "ı" being the classic case
(1.3). A slug generated on one
server must match one generated on another.
⚠️ The length cap matters. An unbounded slug from a long title produces an unwieldy URL and can exceed database index limits.
Catch-all routes for hierarchies¶
When the path depth is not fixed — nested categories, a CMS page tree, a file browser:
// /catalogue/home/furniture/chairs/dining
[HttpGet("catalogue/{**path}")]
public async Task<IActionResult> Browse(string path, CancellationToken ct)
{
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
var category = await _categories.FindByPathAsync(segments, ct);
return category is null ? NotFound() : View(category);
}
Use {**path} rather than {*path} — the double star round-trips through link generation
without re-encoding the slashes (8.4).
⚠️ A catch-all has the lowest routing precedence (8.7), so more specific routes still win:
[HttpGet("catalogue/featured")] // ✓ this wins for /catalogue/featured
[HttpGet("catalogue/{**path}")] // ✓ this handles everything else
That ordering is automatic — you do not have to arrange the registrations.
⚠️ The security issue¶
A catch-all captures anything, including path traversal sequences:
// ✗ CATASTROPHIC
[HttpGet("files/{**path}")]
public IActionResult Download(string path)
{
var full = Path.Combine(_env.ContentRootPath, "uploads", path);
return PhysicalFile(full, "application/octet-stream");
}
Request /files/../../appsettings.json and Path.Combine resolves it — you have just served your
connection strings.
Never build a file system path from a catch-all. Look the file up by identifier instead:
// ✓ The path is a logical key, resolved through the database
[HttpGet("files/{**path}")]
public async Task<IActionResult> Download(string path, CancellationToken ct)
{
var file = await _files.FindByLogicalPathAsync(path, ct);
if (file is null) return NotFound();
// The physical path comes from OUR data, never from the URL
return PhysicalFile(file.StoragePath, file.ContentType, file.OriginalName);
}
If you genuinely must map to disk, validate that the resolved path stays inside the root:
var root = Path.GetFullPath(Path.Combine(_env.ContentRootPath, "uploads"));
var full = Path.GetFullPath(Path.Combine(root, path));
if (!full.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal))
return BadRequest(); // escaped the root — reject it
GetFullPath resolves the .. segments, so comparing afterwards is what makes the check work.
See 17.11.
The deeper detail — SPA fallbacks¶
A single-page app needs unmatched paths to return index.html so client-side routing can handle
them:
⚠️ In an application that also serves an API, that is a trap. A mistyped API URL returns HTML with a 200 status instead of a JSON 404, and the client tries to parse a web page — producing a confusing error a long way from the cause.
Two fixes:
// Or scope the fallback so it never sees /api
app.MapWhen(
ctx => !ctx.Request.Path.StartsWithSegments("/api"),
spa => spa.UseSpaFallback());
The first is simpler and usually enough. :nonfile excludes anything with a file extension,
so /api/ordres still falls through to a proper 404 while /dashboard/settings returns the app
shell.
Code¶
A realistic product controller using ID plus slug:
[Route("products")]
public class ProductsController(IProductService products) : Controller
{
// /products/42 → redirects to the canonical URL
// /products/42/blue-widget → renders
// /products/42/old-name → redirects to the current slug
[HttpGet("{id:int:min(1)}/{slug?}")]
public async Task<IActionResult> Details(int id, string? slug, CancellationToken ct)
{
var product = await products.GetAsync(id, ct);
if (product is null) return NotFound();
if (!string.Equals(slug, product.Slug, StringComparison.Ordinal))
{
// 301 — permanent, so search engines transfer ranking to the canonical URL
return RedirectToActionPermanent(
nameof(Details), new { id, slug = product.Slug });
}
return View(product);
}
// A legacy slug-only URL, kept working for old inbound links
[HttpGet("{slug:minlength(3)}")]
public async Task<IActionResult> BySlug(string slug, CancellationToken ct)
{
var product = await products.GetBySlugAsync(slug, ct);
if (product is null) return NotFound();
// Send everyone to the canonical form
return RedirectToActionPermanent(
nameof(Details), new { id = product.Id, slug = product.Slug });
}
}
Note the precedence at work: {id:int:min(1)} and {slug:minlength(3)} occupy the same position,
and the :int constraint distinguishes them
(8.7). /products/42 matches the first; /products/blue-widget
matches the second.
⚠️ A purely numeric slug would be ambiguous, so if slugs can start with digits you need a
different separator — /products/p-42-blue-widget, or keeping the slug route on a distinct
prefix.
Adding the canonical link tag¶
@* In the view — tells search engines which URL is authoritative *@
<link rel="canonical"
href="@Url.ActionLink("Details", "Products",
new { id = Model.Id, slug = Model.Slug })" />
Generated, not hard-coded (8.6), so changing the route template does not silently break the canonical tag — which would be an SEO problem nobody notices for months.
Interview questions¶
Q: What is a slug and why combine it with an ID?
A slug is the human-readable part of a URL, derived from a title — blue-widget rather than a
GUID. It helps users understand the link and helps search engine ranking. The problem is that
slugs come from titles, and titles change, so a slug-only URL breaks every existing link when
someone renames something — including external links and search results you cannot edit. Putting
the ID first means the lookup is by primary key and always works, with the slug as decoration; a
stale slug just redirects to the current canonical URL rather than 404ing.
Q: How do you handle a slug that has changed?
Look the entity up by ID, compare the slug in the URL to the current one, and if they differ issue
a permanent redirect to the canonical URL. That keeps old links working, consolidates search engine
ranking onto one address rather than splitting it across duplicates, and means /products/42 on
its own also works. I would use a 301 or 308 once the move is genuinely permanent, bearing in mind
browsers cache those aggressively so a mistake is hard to undo.
Q: What is a catch-all route and when would you use it?
A parameter written {**path} that captures the entire remaining path including slashes, rather
than a single segment. It suits genuinely hierarchical URLs where the depth is not fixed — nested
categories, a CMS page tree, a file browser. The double-star form is preferable because it
round-trips through link generation without re-encoding the slashes. Catch-alls have the lowest
routing precedence, so more specific routes still win automatically.
Q: What is the security risk with catch-all routes?
They capture path traversal sequences. A route like files/{**path} will happily receive
../../appsettings.json, and if you pass that to Path.Combine against a root directory it
resolves and you serve your configuration file. So you never build a file system path from a
catch-all — you look the value up as a logical key in your own data and use the physical path that
comes back. If you genuinely must map to disk, resolve with GetFullPath and verify the result is
still inside the root before touching it.
Traps ⚠️¶
- A catch-all captures
../. Never build a file path from one. - Slug-only URLs break when titles change. Use ID plus slug.
ToLoweris culture-sensitive and produces different slugs on different servers. UseToLowerInvariant.- 301 redirects are cached aggressively. A mistake is hard to undo — use 302 while experimenting.
MapFallbackToFilein an API returns HTML with a 200 for mistyped API URLs. Use{*path:nonfile}.- Numeric slugs are ambiguous with an ID route at the same position.
- Slug columns need an index, or lookup is a table scan.
- Unbounded slug length produces unwieldy URLs and can exceed index limits.
- A hard-coded canonical tag breaks silently when the route changes. Generate it.
Related¶
- 8.4 Route templates —
{*path}versus{**path} - 8.5 Route constraints — distinguishing an ID from a slug
- 8.6 Link generation — generating the canonical URL
- 8.7 Endpoint precedence — why a catch-all is last
- 10.3 Status codes — 301 versus 302
- 17.11 Path traversal — the catch-all risk
- 1.3 String comparison — why
ToLowerInvariant - 4.10 Static files — serving files safely