【问题标题】:How to access canonical URL in Next.js with Automatic Static Optimization turned on?如何在打开自动静态优化的情况下访问 Next.js 中的规范 URL?
【发布时间】:2022-02-02 05:52:17
【问题描述】:

我正在开发需要规范 URL 的 SEO 组件。

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

【问题讨论】:

    标签: next.js


    【解决方案1】:

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

    import { useRouter } from "next/router";
    
    const site = "https://gourav.io";
    const canonicalURL = site + useRouter().pathname;
    
    <Head>
      <link rel="canonical" href={canonicalURL} />
    </Head>
    

    【讨论】:

    • 您可能更喜欢使用useRouter().asPath,它甚至适用于dynamic routes。 pathname 将显示为 "/posts/[pid]",而 asPath 将显示为 "/posts/my-post-id",这是您想要的真实 URL。
    • @fzembow 还有一个不同之处。 useRouter().pathname 返回不包括任何查询参数(blog/first-blog)的路径,而 useRouter().asPath 返回包含哈希等的完整路径,例如:blog/first-blog#some-heading
    【解决方案2】:

    在 fzembow's comment 关于 useRouter().asPath 和 GorvGoyl's answer 的基础上,这是一个管理动态路由并排除锚和查询参数 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>
    

    【讨论】:

      【解决方案3】:

      使用名为 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',
          },
        };
      };
      

      【讨论】:

        【解决方案4】:

        一个超级丑陋的,然而,我找到的最合适的解决方案:

        const canonicalUrl = typeof window === 'undefined' ?
          '' :
          `${window.location.origin}/${window.location.pathname}`;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-14
          • 2013-11-10
          • 1970-01-01
          • 1970-01-01
          • 2021-12-17
          • 2020-05-01
          相关资源
          最近更新 更多