Skip to content

Commit b722317

Browse files
committed
修 sitemap.xml 404 因 nuxt sitemap v7 + i18n + baseURL 已知 bug 改用 postgenerate 腳本把 redirect 目錄轉為真檔案
1 parent da2ce81 commit b722317

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

site/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
"type": "module",
66
"scripts": {
77
"sync-docs": "node scripts/sync-docs.mjs",
8+
"fix-sitemap": "node scripts/fix-sitemap.mjs",
89
"predev": "node scripts/sync-docs.mjs",
910
"pregenerate": "node scripts/sync-docs.mjs",
11+
"postgenerate": "node scripts/fix-sitemap.mjs",
1012
"prebuild": "node scripts/sync-docs.mjs",
1113
"build": "nuxt build",
1214
"dev": "nuxt dev",

site/scripts/fix-sitemap.mjs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/env node
2+
// 修 @nuxtjs/sitemap v7 + i18n + baseURL 已知 bug:
3+
// 預設 sitemap.xml 變成 HTML meta-refresh 重導到 /sitemap_index.xml,
4+
// 但 redirect URL 缺 baseURL 前綴 → 爬蟲 follow 後 404。
5+
//
6+
// 此腳本在 nuxt generate 之後執行(postgenerate hook):
7+
// 1. 刪掉 .output/public/sitemap.xml/ 目錄 (含內部的 redirect index.html)
8+
// 2. 把 .output/public/sitemap_index.xml 的內容複製成 .output/public/sitemap.xml
9+
//
10+
// Google/Bing 都接受 sitemap.xml 本身為 sitemap index 檔案,不需另外指向。
11+
12+
import fs from 'node:fs'
13+
import path from 'node:path'
14+
import { fileURLToPath } from 'node:url'
15+
16+
const __dirname = path.dirname(fileURLToPath(import.meta.url))
17+
const SITE_DIR = path.resolve(__dirname, '..')
18+
const PUBLIC_DIR = path.join(SITE_DIR, '.output', 'public')
19+
20+
const sitemapXmlDir = path.join(PUBLIC_DIR, 'sitemap.xml')
21+
const sitemapIndexFile = path.join(PUBLIC_DIR, 'sitemap_index.xml')
22+
const sitemapXmlFile = sitemapXmlDir // will become a file after fix
23+
24+
if (!fs.existsSync(PUBLIC_DIR)) {
25+
console.error(`[fix-sitemap] .output/public not found — run nuxt generate first`)
26+
process.exit(1)
27+
}
28+
29+
if (!fs.existsSync(sitemapIndexFile)) {
30+
console.error(`[fix-sitemap] sitemap_index.xml not found — sitemap module did not generate it`)
31+
process.exit(1)
32+
}
33+
34+
// 1. 若 sitemap.xml 是目錄,移除它
35+
if (fs.existsSync(sitemapXmlDir)) {
36+
const stat = fs.statSync(sitemapXmlDir)
37+
if (stat.isDirectory()) {
38+
fs.rmSync(sitemapXmlDir, { recursive: true, force: true })
39+
console.log('[fix-sitemap] removed buggy sitemap.xml/ redirect directory')
40+
} else if (stat.isFile()) {
41+
// 已經是檔案(可能其他工具修過了),跳過
42+
console.log('[fix-sitemap] sitemap.xml already a file — skipping')
43+
process.exit(0)
44+
}
45+
}
46+
47+
// 2. 把 sitemap_index.xml 內容複製成 sitemap.xml
48+
fs.copyFileSync(sitemapIndexFile, sitemapXmlFile)
49+
const size = fs.statSync(sitemapXmlFile).size
50+
console.log(`[fix-sitemap] sitemap.xml now contains sitemap index (${size} bytes)`)

0 commit comments

Comments
 (0)