Fix canonical URL for blog posts to use pretty URL format
This commit is contained in:
parent
462b941b71
commit
8d707b6683
3 changed files with 30 additions and 19 deletions
|
|
@ -21,10 +21,12 @@ interface Props {
|
|||
|
||||
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
|
||||
|
||||
// For pretty URLs (e.g., /slug), use the pretty URL as canonical
|
||||
const requestedPath = Astro.request.url.replace(Astro.site?.href || '', '/').replace(/\/$/, '');
|
||||
const isPrettyUrl = requestedPath.startsWith('/20') || /^\/\d{4}-/.test(requestedPath);
|
||||
const finalCanonicalPath = isPrettyUrl ? requestedPath : Astro.url.pathname;
|
||||
// For blog posts with date-slug format, show pretty URL in og:url/canonical
|
||||
// This handles both direct /slug access and proxy /blog/slug access
|
||||
const pathParts = Astro.url.pathname.split('/').filter(Boolean);
|
||||
const blogPostMatch = pathParts[0] === 'blog' ? pathParts[1] : pathParts[0];
|
||||
const isBlogPost = blogPostMatch?.match(/^\d{4}-\d{2}-\d{2}-/);
|
||||
const finalCanonicalPath = isBlogPost ? `/${blogPostMatch}` : Astro.url.pathname;
|
||||
const finalCanonicalURL = new URL(finalCanonicalPath, Astro.site);
|
||||
|
||||
const { title, description, image = "/astro-micro.jpg" } = Astro.props;
|
||||
|
|
|
|||
23
src/pages/[...id].astro
Normal file
23
src/pages/[...id].astro
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
---
|
||||
import { getCollection } from 'astro:content';
|
||||
|
||||
export async function getStaticPaths() {
|
||||
const posts = await getCollection('blog');
|
||||
|
||||
// Generate paths for both /blog/slug and /slug
|
||||
const paths = [];
|
||||
|
||||
for (const post of posts) {
|
||||
// /blog/slug - the original path
|
||||
paths.push({
|
||||
params: { id: post.id },
|
||||
props: { slug: post.id },
|
||||
});
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
const { slug } = Astro.props;
|
||||
return Astro.redirect(`/blog/${slug}`, 301);
|
||||
---
|
||||
Loading…
Add table
Add a link
Reference in a new issue