13
章节13
URL 结构
URL 结构是 SEO 策略的重要组成部分。虽然 Google 没有披露 SEO 各部分的比重,但无论它们最终是重要还是次要的排名因素,优秀的 URL 都被认为是最佳实践。
您可能需要遵循一些原则
- 语义化:最好使用语义化的 URL,这意味着它们使用单词而不是 ID 或随机数字。例如:
/learn/basics/create-nextjs-app比/learn/course-1/lesson-1更好 - 逻辑且一致的模式:URL 应该遵循某种在页面之间保持一致的模式。例如,您希望有一个文件夹来分组所有产品页面,而不是为您拥有的每个产品使用不同的路径。
- 以关键词为中心:Google 的系统仍然有相当一部分是基于网站所包含的关键词。您可能希望在 URL 中使用关键词,以便于理解页面的目的。
- 非基于参数:使用参数来构建 URL 通常不是一个好主意。在大多数情况下,它们不具有语义性,并且搜索引擎可能会混淆它们并降低其在结果中的排名。
Next.js 中如何定义路由?
Next.js 使用基于页面概念的文件系统路由。当文件添加到pages目录时,它会自动作为路由可用。pages目录中的文件和文件夹可用于定义大多数常见模式。
让我们看看几个简单的 URL 以及如何将它们添加到 Next.js 路由器中
- 主页:
https://www.example.com→pages/index.js - 列表页:
https://www.example.com/products→pages/products.js或pages/products/index.js - 详情页:
https://www.example.com/products/product→pages/products/product.js
对于博客或电子商务网站,您可能希望将产品 ID 或博客名称用作 URL 的 slug。这称为动态路由
- 产品:
https://www.example.com/products/nextjs-shirt→pages/products/[product].js - 博客:
https://www.example.com/blog/seo-in-nextjs→pages/blog/[blog-name].js
要使用动态路由,您可以在products或blogs子文件夹内的页面名称中添加方括号。
这是一个使用 SSG 优化的页面示例
// pages/blog/[slug].js
import Head from 'next/head';
export async function getStaticPaths() {
// Call an external API endpoint to get posts
const res = await fetch('https://www.example.com/api/posts');
const posts = await res.json();
// Get the paths we want to pre-render based on posts
const paths = posts.map((post) => ({
params: { slug: post.slug },
}));
// Set fallback to blocking. Now any new post added post build will SSR
// to ensure SEO. It will then be static for all subsequent requests
return { paths, fallback: 'blocking' };
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://www.example.com/api/blog/${params.slug}`);
const data = await res.json();
return {
props: {
blog: data,
},
};
}
function BlogPost({ blog }) {
return (
<>
<Head>
<title>{blog.title} | My Site</title>
</Head>
<div>
<h1>{blog.title}</h1>
<p>{blog.text}</p>
</div>
</>
);
}
export default BlogPost;这是另一个使用 SSR 的示例
// pages/blog/[slug].js
import Head from 'next/head';
function BlogPost({ blog }) {
return (
<div>
<Head>
<title>{blog.title} | My Site</title>
</Head>
<div>
<h1>{blog.title}</h1>
<p>{blog.text}</p>
</div>
</div>
);
}
export async function getServerSideProps({ query }) {
const res = await fetch(`https://www.example.com/api/blog/${query.slug}`);
const data = await res.json();
return {
props: {
blog: data,
},
};
}
export default BlogPost;延伸阅读
这有帮助吗?