Next.js 将 www 重定向到非 www

Next.js redirect www to non www

我一直在尝试通过搜索 google 找到可行的解决方案,但找不到任何可靠的解决方案。我正在 Vercel 上托管我的 Next.js 应用程序。

当我 运行 搜索引擎优化检查它抱怨我在 www 和非 www 上都可以访问该网站并说我应该选择一个并让它重定向 所以在我的情况下,如果有人输入 www.example.com 我希望它位于 www.

的左侧

由于我没有 htaccess 文件,我可以在其中执行此操作,我该怎么做?

不确定这是否重要,但我使用 WordPress 作为我的后端又名:Headless Wordpress

您可以使用下面提到的代码在 nextjs 中轻松处理永久重定向。

export const getServerSideProps = async (context) => {
    const { req, res } = context;

    if (req.headers.host.match(/^www/) !== null) {
        res.writeHead(301, {
            location: "https://" + req.headers.host.replace(/^www./, "") + req.url,
        });
        res.end();
    }

    return { props: {} };
};

从 Next v10.2 开始,您现在应该可以使用基于主机的重定向。参见 https://nextjs.org/docs/api-reference/next.config.js/redirects#header-cookie-and-query-matching

在next.config.js中:

module.exports = {
  // ...
  redirects: async () => [
    {
      source: '/:path*',
      has: [{ type: 'host', value: 'www.yourdomain.com' }],
      destination: 'https://yourdomain.com/:path*',
      permanent: true
    }
  ]
}