Files
web-temp/layers/server/routes/robots.txt.ts
2025-09-18 20:08:41 +09:00

89 lines
2.5 KiB
TypeScript

// server/routes/robots.txt.ts
type RobotsConfig = {
userAgent?: string | string[]
allow?: string[]
disallow?: string[]
sitemap?: string | string[]
host?: string
cache?: { sMaxAge?: number; staleWhileRevalidate?: number }
}
export default defineEventHandler(async event => {
const host =
(getHeader(event, 'host') || getRequestHost(event)).toString() || ''
const baseDomain = process.env.BASE_DOMAIN || '.onstove.com'
const isGameAliasExtractable = host.includes(baseDomain)
let gameAlias = ''
if (isGameAliasExtractable) {
gameAlias = host.split('.')[0]
}
// if (gameAlias && gameAlias !== "www") {
// event.context.gameAlias = gameAlias;
// }
// }
// robots 설정을 직접 가져오기 (미들웨어 context 사용)
let config: RobotsConfig
try {
// robots 설정 추출
config = {
userAgent: '*',
allow: ['/'],
disallow: ['/error', '/inspection/', '/inspection/*', '/html/*'],
sitemap: [
`https://static-pubcomm.gate8.com/local/template/${gameAlias}/sitemap.xml`,
],
host: `${gameAlias}.onstove.com`,
cache: { sMaxAge: 300, staleWhileRevalidate: 600 },
}
} catch (error) {
console.error('Failed to fetch robots config:', error)
// 에러 발생 시 기본값 반환
config = {
userAgent: '*',
allow: ['/'],
disallow: ['/error', '/inspection/', '/inspection/*', '/html/*'],
cache: { sMaxAge: 300, staleWhileRevalidate: 600 },
}
}
setHeader(event, 'Content-Type', 'text/plain; charset=utf-8')
// 캐시 헤더 (CDN 친화)
const sMax = config.cache?.sMaxAge ?? 300
const swr = config.cache?.staleWhileRevalidate ?? 600
setHeader(
event,
'Cache-Control',
`public, s-maxage=${sMax}, stale-while-revalidate=${swr}`
)
// 여러 user-agent 지원
const agents = Array.isArray(config.userAgent)
? config.userAgent
: [config.userAgent ?? '*']
const lines: string[] = []
for (const ua of agents) {
lines.push(`User-agent: ${ua}`)
for (const p of config.allow ?? []) lines.push(`Allow: ${p}`)
for (const p of config.disallow ?? []) lines.push(`Disallow: ${p}`)
lines.push('') // 블록 구분 공백
}
const sitemaps = Array.isArray(config.sitemap)
? config.sitemap
: config.sitemap
? [config.sitemap]
: []
for (const sm of sitemaps) lines.push(`Sitemap: ${sm}`)
if (config.host) lines.push(`Host: ${config.host}`)
// 마지막 개행
return lines.join('\n').trim() + '\n'
})