我正在搜索引擎优化组件,这需要一个规范的网址。
如何在启用自动静态优化的Next.js中获取静态页面的URL?
发布于 2020-12-01 02:06:44
使用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>发布于 2021-05-06 00:13:26
在关于useRouter().asPath和GorvGoyl's answer的fzembow's comment的基础上,这里有一个实现,它设法处理动态路由,并排除锚点和查询参数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>发布于 2020-09-15 19:42:56
使用名为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',
},
};
};https://stackoverflow.com/questions/61574405
复制相似问题