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

jdgnovmf  于 2022-11-23  发布在  其他
关注(0)|答案(6)|浏览(145)

我正在工作的SEO组件,需要一个规范的URL。
我怎样才能在Next.js中获得打开了自动静态优化的静态页面的URL?

vmpqdwk3

vmpqdwk31#

使用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>
w8f9ii69

w8f9ii692#

基于fzembow关于useRouter().asPathGorvGoyl'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>
wnvonmuf

wnvonmuf3#

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

qv7cva1a4#

一个超级丑陋的,然而,最充分的解决方案我发现:

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

ubby3x7f5#

我的解决方案是将新的URL与router.asPath一起使用。

const CURRENT_URL = process.env.NEXT_PUBLIC_CURRENT_SITE_URL

    const getCanonical = (path: string) => {
      const fullURL = new URL(path, CURRENT_URL)
      return`${fullURL.origin}${fullURL.pathname}
    }

    export const Page = () => {
      const router = useRouter()
      const canonical = getCanonical(router.asPath)

      <Head>
        <link rel="canonical" href={canonical} />
      </Head>
      <div>
      ...
      <div>
    }
bis0qfac

bis0qfac6#

我在_app.js中添加了一个规范的链接标记,以便它出现在每个页面上:

<link
   rel="canonical"
   href={typeof window !== 'undefined' && `${window.location.origin}${useRouter().asPath}`}
   key="canonical"
/>

相关问题