我们正在使用 Next.js,并希望根据浏览器标头将所有路径(不仅仅是根路径)路由到基于区域设置的路径Accept-Language
。但是,如果用户设置他们的区域,我们将设置一个 cookie,需要首先检查以尊重用户偏好。
因此,我们需要检查 cookie,如果不存在,请尝试基于浏览器语言标头进行重定向。我们使用的是 ISG,因此仅限于 next.config.js 重定向服务器端。
根据文档,这应该可以,但是由于我们使用的是 ISG,因此我们需要在next.config.js
重定向功能中执行此操作。
我们已经尝试过这个解决方案,但它不起作用(我们得到无限重定向,因为 cookie 和标头匹配):
const { i18n } = require('./next-i18next.config');
const withTM = require('next-transpile-modules')(['fitty', 'react-svg']); // pass the modules you would like to see transpiled
const handleLocaleRedirects = (path) => {
const result = [];
i18n.locales.forEach((locale) => {
i18n.locales.forEach((loc) => {
if (loc !== locale) {
result.push({
source: `/${locale}${path}`,
has: [
{
type: 'header',
key: 'accept-language',
value: `^${loc}(.*)`,
},
],
permanent: false,
locale: false,
destination: `/${loc}${path}`,
});
result.push({
source: `/${locale}${path}`,
has: [
{
type: 'cookie',
key: 'NEXT_LOCALE',
value: loc,
},
],
permanent: true,
locale: false,
destination: `/${loc}${path}`,
});
}
});
});
return result;
};
module.exports = withTM({
i18n,
reactStrictMode: true,
images: {
domains: [
'dxjnh2froe2ec.cloudfront.net',
'starsona-stb-usea1.s3.amazonaws.com',
],
},
eslint: {
// Warning: Dangerously allow production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
async redirects() {
return [...handleLocaleRedirects('/:celebrityId')];
},
});