服务端渲染(SSR) 对国际化 SEO 表现至关重要。本技术指南涵盖了多语言站点的 SSR 策略与性能优化。
为什么 SSR 对国际化 SEO 很重要
| 优势 | 影响 |
|---|---|
| 更快的 FCP/LCP | 更优的 Core Web Vitals 分数 |
| HTML 中包含 hreflang | 搜索引擎能发现所有语言版本 |
| 正确的 meta 标签 | 每种语言都有正确的标题/描述 |
| 结构化数据 | 服务端渲染,可即时解析 |
Next.js 国际化 SSR
// next.config.js
const nextConfig = {
i18n: {
locales: ["en-US", "de-DE", "fr-FR", "ja-JP", "zh-CN"],
defaultLocale: "en-US",
localeDetection: true,
},
trailingSlash: true,
};
module.exports = nextConfig;
// pages/[locale]/articles/[slug].js
export async function getServerSideProps({ params, locale }) {
const { slug } = params;
const article = await fetchArticle(slug, locale);
if (!article) return { notFound: true };
const locales = ["en-US", "de-DE", "fr-FR", "ja-JP", "zh-CN"];
const hreflangTags = locales.map((loc) => ({
hreflang: loc,
href: "https://example.com/" + loc + "/articles/" + slug,
}));
return { props: { article, locale, hreflangTags } };
}
基于用户地理位置的动态渲染
Cloudflare Worker
export default {
async fetch(request) {
const country = request.cf.country;
const url = new URL(request.url);
const countryLocaleMap = {
US: "en-US", GB: "en-GB", DE: "de-DE",
FR: "fr-FR", JP: "ja-JP", CN: "zh-CN",
};
const preferredLocale = countryLocaleMap[country] || "en-US";
if (url.pathname === "/" && !request.headers.get("cookie")?.includes("locale=")) {
return Response.redirect(url.origin + "/" + preferredLocale + "/", 302);
}
return fetch(request);
},
};
面向国际化站点的 CDN 策略
cdn:
provider: cloudflare
caching:
rules:
- path: "/en/*"
edge_ttl: 86400
- path: "/de/*"
edge_ttl: 86400
geo_routing:
- country: [DE, AT, CH]
origin: eu-west-1
- country: [JP, KR]
origin: ap-northeast-1
- default: us-east-1
监控国际化 SSR 性能
import { onLCP, onINP, onCLS } from "web-vitals";
function sendToAnalytics(metric) {
const locale = document.documentElement.lang || "unknown";
const body = JSON.stringify({ name: metric.name, value: metric.value, locale: locale });
navigator.sendBeacon("/api/vitals", body);
}
onLCP(sendToAnalytics);
onINP(sendToAnalytics);
onCLS(sendToAnalytics);
结论
服务端渲染对国际化 SEO 至关重要。它确保搜索引擎能够抓取所有语言版本,同时让用户获得快速、本地化的内容。