Files
web-temp/layers/server/routes/robots.txt.ts

88 lines
2.4 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
const isGameAliasExtractable = host.includes(baseDomain)
let gameAlias = ''
if (isGameAliasExtractable) {
gameAlias = host.split('.')[0].replace(/-dev$/, '')
}
let config: RobotsConfig
try {
const staticUrl = process.env.STATIC_URL
const runType = process.env.RUN_TYPE
// gameAlias가 있을 때만 sitemap 포함
const sitemapUrl = gameAlias
? [`${staticUrl}/${runType}/template/${gameAlias}/sitemap.xml`]
: undefined
config = {
userAgent: '*',
allow: ['/'],
disallow: ['/error', '/inspection/*', '/html/*'],
sitemap: sitemapUrl,
host: gameAlias ? `${gameAlias}.onstove.com` : undefined,
cache: { sMaxAge: 300, staleWhileRevalidate: 600 },
}
} catch (error) {
console.error('Failed to fetch robots config:', error)
// 에러 발생 시 기본값 반환
config = {
userAgent: '*',
allow: ['/'],
disallow: ['/error', '/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'
})