feat: add sitemap generation for SEO enhancement

Implements dynamic sitemap generation to improve SEO by providing search engines with updated site structure and content availability. This includes a root sitemap index and paginated sitemap files for individual posts, enhancing crawl efficiency and content discoverability.
This commit is contained in:
ccbikai
2024-08-05 12:04:34 +08:00
parent 8d8f7de19c
commit 10fe7b3da3
3 changed files with 67 additions and 0 deletions

3
public/robots.txt Normal file
View File

@@ -0,0 +1,3 @@
User-agent: *
Sitemap: /sitemap.xml

36
src/pages/sitemap.xml.js Normal file
View File

@@ -0,0 +1,36 @@
import { getChannelInfo } from '../lib/telegram'
export const prerender = false
export async function GET(Astro) {
const request = Astro.request
const url = new URL(request.url)
const channel = await getChannelInfo(Astro)
const posts = channel.posts || []
const pageSize = 20
let count = +posts[0]?.id
const pages = []
pages.push(count)
while (count > pageSize) {
count -= pageSize
pages.push(count)
}
const sitemaps = pages.map((page) => {
return `
<sitemap>
<loc>${url.origin}/sitemap/${page}.xml</loc>
</sitemap>`
})
return new Response(`<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${sitemaps.join('')}
</sitemapindex>`, {
headers: {
'Content-Type': 'application/xml',
},
})
}

View File

@@ -0,0 +1,28 @@
import { getChannelInfo } from '../../lib/telegram'
export const prerender = false
export async function GET(Astro) {
const request = Astro.request
const url = new URL(request.url)
const channel = await getChannelInfo(Astro, {
before: Astro.params.cursor,
})
const posts = channel.posts || []
const xmlUrls = posts.map(post => `
<url>
<loc>${url.origin}/posts/${post.id}</loc>
<lastmod>${new Date(post.datetime).toISOString()}</lastmod>
</url>
`).join('')
return new Response(`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${xmlUrls}
</urlset>`, {
headers: {
'Content-Type': 'application/xml',
},
})
}