如何在NextJS中使用不同的url为相同的静态页面?

  • 本文关键字:静态 url NextJS next.js locale
  • 更新时间 :
  • 英文 :


我正在使用next-i18next构建一个具有国际化的Next.js应用程序。

// next-i18next.config.js
module.exports = {
i18n: {
locales: ['lv', 'en', 'ua'],
defaultLocale: 'lv',
localeDetection: false,
},
}

为了更好的SEO,我想为相同的翻译页面使用不同的URL参数。默认的NextJS页面/语言环境映射如下所示:

lv: /about-us
en: /en/about-us
ua: /ua/about-us

我想这样映射这个页面:

lv: /par-mums
en: /en/about-us
ua: /ua/про-нас

这可能吗?谢谢!

如果你想用Next.js创建一个国际化的静态网站,请确保你知道Next.js的导出能力有限:

错误:i18n支持与下次导出不兼容。请看这里更多关于部署的信息:https://nextjs.org/docs/deployment

有一个很好的解决方法:https://locize.com/blog/next-i18n-static/

顺便说一句:这里还有一个很好的教程和例子:https://locize.com/blog/next-i18next/

首先我很抱歉我不知道如何获得语言代码

但是我想让你试试这个

if (local == 'en') {
return NextResponse.redirect('/en/about-us')
}

这样的

也许我不需要担心URL。在_app.js中,我映射了同一页面的本地化版本。因此,serp应该了解其他版本。

...
{locales.map((name, index) => {
return (
defaultLocale === name ?
(<link key={`locale-${index}`} rel="alternate" hrefLang="x-default" href={`${process.env.NEXT_PUBLIC_SITE_URL}${pathname}`} />):
(<link key={`locale-${index}`} rel="alternate" hrefLang={name} href={`${process.env.NEXT_PUBLIC_SITE_URL}/${name}${pathname}`} />)
)
})
}

https://developers.google.com/search/docs/advanced/crawling/localized-versions

您可以使用exportPathMap。使用此方法,您可以按语言生成不同的静态html。您的静态页面大小将增长两倍,但它是有效的,没有任何影响页面加载速度。

你的自定义Link组件:

import i18n from 'i18next'
import Link from 'next/link'
interface IProps {
fr: string
en: string
children: React.ReactNode
}
export default function TranslatedLink({ fr, en, children }: IProps) {
let link = fr
if (i18n.language === 'en') {
link = en
}
return <Link href={link}>{children}</Link>
}

你的链接:

<TranslatedLink fr="/contactez" en="contact>Contact</TranslatedLink>
在next.config.js

exportPathMap: async function () {
return {
'/contact': { page: '/contact' },
'/contactez': { page: '/contact/ }
}
}

要在本地运行,将此添加到next.config.js中:

async rewrites() {
return [
{
source: '/contactez',
destination: '/contact',
},
}

最新更新