import { defineEventHandler, getRequestURL, sendRedirect } from 'h3' // @ts-ignore: runtime module from @nuxt/content import { queryContent } from '#content/server' export default defineEventHandler(async (event) => { const url = getRequestURL(event) const path = url.pathname // Match top-level locale-prefixed paths like /en/slug, /zh/slug, /zh-hant/slug const match = path.match(/^\/(en|zh|zh-hant)(\/.*)$/) if (!match) return const locale = match[1] const rest = match[2] // includes leading '/' try { // Check if a content doc exists for this locale and slug const doc = await queryContent(event) .where({ _locale: locale, _path: `/${locale}${rest}` }) .findOne() // If not found by _path, also try querying by normalized path with _locale filter const normalized = rest // e.g., /getting-started-aws-ec2 const fallback = doc || await queryContent(event) .where({ _locale: locale }) .path(normalized) .findOne() if (fallback) { const appPrefix = locale === 'en' ? '' : `/${locale}` const target = `${appPrefix}/blog${rest}` // 301 permanent redirect return sendRedirect(event, target, 301) } } catch { // Ignore errors and let normal routing continue } })