Skip to content

Commit b07904f

Browse files
authored
Add preservePath option for redirects and implement /git redirect (#222)
- Add preservePath field to redirect schemas for prefix-based redirects - Implement preservePath logic in middleware to append remaining path to target URL - Add /git redirect to https://github.com/just-be-dev with preservePath enabled - Enables short GitHub URLs like /git/repo-name to redirect to org repositories
1 parent bc000ad commit b07904f

4 files changed

Lines changed: 25 additions & 1 deletion

File tree

src/content.config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ const redirects = defineCollection({
9292
data: {
9393
to: redirect.to,
9494
permanent: redirect.permanent ?? false,
95+
preservePath: redirect.preservePath ?? false,
9596
},
9697
});
9798
}

src/content/redirects.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,8 @@ redirects:
22
- from: /chat
33
to: https://savvycal.com/just-be/chat
44
permanent: true
5+
6+
- from: /git
7+
to: https://github.com/just-be-dev
8+
permanent: true
9+
preservePath: true

src/content/schemas.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ export const urlsSchema = z.object({
7474
export const redirectsSchema = z.object({
7575
to: z.string().url(),
7676
permanent: z.boolean(),
77+
preservePath: z.boolean().optional(),
7778
});
7879

7980
// Schema for the redirects YAML file structure
@@ -83,6 +84,7 @@ export const redirectsFileSchema = z.object({
8384
from: z.string().startsWith("/"),
8485
to: z.string().url(),
8586
permanent: z.boolean().optional(),
87+
preservePath: z.boolean().optional(),
8688
}),
8789
),
8890
});

src/middleware.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,23 @@ export const onRequest = defineMiddleware(async (context, next) => {
77

88
// Handle redirects from redirects collection
99
const redirects = await getCollection("redirects");
10-
const redirect = redirects.find((r) => r.id === url.pathname);
10+
11+
// First try exact match
12+
let redirect = redirects.find((r) => r.id === url.pathname);
13+
14+
// If no exact match, try prefix matches with preservePath
15+
if (!redirect) {
16+
for (const r of redirects) {
17+
if (r.data.preservePath && url.pathname.startsWith(r.id)) {
18+
const remainingPath = url.pathname.slice(r.id.length);
19+
const target = r.data.to + remainingPath;
20+
const status = r.data.permanent ? 301 : 302;
21+
return context.redirect(target, status);
22+
}
23+
}
24+
}
25+
26+
// Handle exact match redirect
1127
if (redirect) {
1228
const status = redirect.data.permanent ? 301 : 302;
1329
return context.redirect(redirect.data.to, status);

0 commit comments

Comments
 (0)