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)
使用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)
小智 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)
| 归档时间: |
|
| 查看次数: |
3088 次 |
| 最近记录: |