diff --git a/CHANGELOG.md b/CHANGELOG.md index 97220aaa..bd927b6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ Go to the `v1` branch to see the changelog of Lume 1. ### Added - New option `caseSensitiveUrls` to allow to export two urls with the same name but different cases [#625]. - Support for `npm` specifiers to postcss and lightningcss plugins [#621]. +- Redirects middleware: added `strict` option. ### Changed - Nav plugin: Improved behavior for sites with pretty urls disabled. diff --git a/middlewares/redirects.ts b/middlewares/redirects.ts index 2fa46fc9..22fd7783 100644 --- a/middlewares/redirects.ts +++ b/middlewares/redirects.ts @@ -1,7 +1,10 @@ import type { Middleware } from "../core/server.ts"; export interface Options { + /** A map of redirects */ redirects: Record; + /** Whether distinguish the trailing slash or not */ + strict?: boolean; } export interface Redirect { @@ -17,9 +20,21 @@ export default function redirects(options: Options): Middleware { redirects.set(from, buildRedirects(to)); } + const strict = options.strict ?? true; + + function findRedirect(url: string): Redirect | undefined { + if (strict) { + return redirects.get(url); + } + + // Remove the trailing slash + const cleaned = url === "/" ? url : url.replace(/\/$/, ""); + return redirects.get(cleaned) || redirects.get(cleaned + "/"); + } + return async (request, next) => { const url = new URL(request.url); - const redirect = redirects.get(url.pathname) || redirects.get(url.href); + const redirect = findRedirect(url.pathname) || findRedirect(url.href); if (!redirect) { return await next(request);