【发布时间】:2022-02-02 05:52:17
【问题描述】:
我正在开发需要规范 URL 的 SEO 组件。
在开启自动静态优化的情况下,如何在 Next.js 中获取静态页面的 URL?
【问题讨论】:
标签: next.js
我正在开发需要规范 URL 的 SEO 组件。
在开启自动静态优化的情况下,如何在 Next.js 中获取静态页面的 URL?
【问题讨论】:
标签: next.js
使用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。
useRouter().pathname 返回不包括任何查询参数(blog/first-blog)的路径,而 useRouter().asPath 返回包含哈希等的完整路径,例如:blog/first-blog#some-heading
在 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>
【讨论】:
使用名为 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',
},
};
};
【讨论】:
一个超级丑陋的,然而,我找到的最合适的解决方案:
const canonicalUrl = typeof window === 'undefined' ?
'' :
`${window.location.origin}/${window.location.pathname}`;
【讨论】: