Skip to content

Commit

Permalink
added strict option to redirects middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarotero committed Jul 5, 2024
1 parent 5ae7b47 commit e3e4bc9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 16 additions & 1 deletion middlewares/redirects.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import type { Middleware } from "../core/server.ts";

export interface Options {
/** A map of redirects */
redirects: Record<string, string | Redirect>;
/** Whether distinguish the trailing slash or not */
strict?: boolean;
}

export interface Redirect {
Expand All @@ -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);
Expand Down

0 comments on commit e3e4bc9

Please sign in to comment.