如何在启用自动静态优化的情况下访问 Next.js 中的规范 URL?

cur*_*ous 7 next.js

我正在研究需要规范 URL 的 SEO 组件。

如何在启用自动静态优化的情况下在 Next.js 中获取静态页面的 URL?

bsp*_*ion 10

基于fzembow 的评论useRouter().asPathGorvGoyl的回答,这里有一个实现,它能够处理动态路由并排除锚点和查询参数 URL 扩展:

import { useRouter } from "next/router";

const CANONICAL_DOMAIN = 'https://yoursite.com';

const router = useRouter();
const _pathSliceLength = Math.min.apply(Math, [
    router.asPath.indexOf('?') > 0 ? router.asPath.indexOf('?') : router.asPath.length,
    router.asPath.indexOf('#') > 0 ? router.asPath.indexOf('#') : router.asPath.length
]);
const canonicalURL= CANONICAL_DOMAIN + router.asPath.substring(0, _pathSliceLength);

<Head>
  <link rel="canonical" href={ canonicalURL } />
</Head>
Run Code Online (Sandbox Code Playgroud)


Jer*_*yal 8

使用useRouterfromnext/router可以获得pathname当前页面的 并在<Head/>标签中使用它,如下所示:

import { useRouter } from "next/router";

const site = "https://gourav.io";
const canonicalURL = site + useRouter().pathname;

<Head>
  <link rel="canonical" href={canonicalURL} />
</Head>
Run Code Online (Sandbox Code Playgroud)

  • 您可能更喜欢使用“useRouter().asPath”,它甚至适用于[动态路由](https://nextjs.org/docs/routing/dynamic-routes)。`pathname` 将显示为 `"/posts/[pid]"`,而 `asPath` 将显示为 `"/posts/my-post-id"`,这就是您想要的真实 URL。 (3认同)
  • @fzembow 还有一个区别。`useRouter().pathname` 返回不包括任何查询参数(blog/first-blog)的路径,而 `useRouter().asPath` 返回包括哈希值等的完整路径,例如:blog/first-blog#some-heading (2认同)

小智 0

使用名为 next-absolute-url 的包。它在 getServerSideProps 中工作。由于 getStaticProps 在构建时运行,因此没有可用数据。可以用作

export const getServerSideProps: GetServerSideProps = async (ctx) => {
 const { req, query } = ctx;
   const { origin } = absoluteUrl(req);      
      return {
        props: {
          canonicalUrl: `${origin}/user-listings`,
        },
      };
    };

export const getStaticProps:GetStaticProps = async (ctx) => {
  return {
    props: {
      canonicalUrl: 'https://www.test.com',
    },
  };
};
Run Code Online (Sandbox Code Playgroud)