refactor: optimize root redirect mechanism to prevent white screen

This commit is contained in:
2025-12-24 12:12:05 +08:00
parent a5b060a777
commit 1423374218
3 changed files with 37 additions and 31 deletions

View File

@@ -11,6 +11,7 @@ export default defineConfig({
locales: ["en", "zh-cn"],
routing: {
prefixDefaultLocale: true,
redirectToDefaultLocale: false,
},
},
});

36
src/pages/index.astro Normal file
View File

@@ -0,0 +1,36 @@
---
import Layout from "../layouts/Layout.astro";
export const prerender = false;
const acceptLang = Astro.request.headers.get("accept-language") || "";
let targetUrl = "/en/";
// Parse and sort languages by quality (q)
// Example: "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
const languages = acceptLang
.split(",")
.map((part) => {
const [code, qPart] = part.split(";");
const q = qPart ? parseFloat(qPart.split("=")[1]) : 1.0;
return { code: code.trim().toLowerCase(), q };
})
.sort((a, b) => b.q - a.q);
for (const lang of languages) {
if (lang.code.startsWith("zh")) {
targetUrl = "/zh-cn/";
break;
}
if (lang.code.startsWith("en")) {
targetUrl = "/en/";
break;
}
}
---
<Layout title="Loading...">
<script is:inline define:vars={{ targetUrl }}>
window.location.replace(targetUrl);
</script>
</Layout>

View File

@@ -1,31 +0,0 @@
import type { APIRoute } from "astro";
export const prerender = false;
export const GET: APIRoute = ({ request, redirect }) => {
const acceptLang = request.headers.get("accept-language") || "";
// Parse and sort languages by quality (q)
// Example: "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
const languages = acceptLang
.split(",")
.map((part) => {
const [code, qPart] = part.split(";");
const q = qPart ? parseFloat(qPart.split("=")[1]) : 1.0;
return { code: code.trim().toLowerCase(), q };
})
.sort((a, b) => b.q - a.q);
// Iterate through user's preferred languages in order
for (const lang of languages) {
if (lang.code.startsWith("zh")) {
return redirect("/zh-cn/");
}
if (lang.code.startsWith("en")) {
return redirect("/en/");
}
}
// Fallback to default
return redirect("/en/");
};