Skip to content

Next.js SEO 优化 🔍

🎯 概述

SEO(搜索引擎优化)对于网站的可见性至关重要。Next.js 提供了强大的 SEO 优化功能。

📦 元数据 API

静态元数据

tsx
// app/page.tsx
import { Metadata } from 'next'

export const metadata: Metadata = {
  title: '首页 | 我的网站',
  description: '欢迎来到我的网站',
  keywords: ['Next.js', 'React', 'SEO'],
}

export default function Page() {
  return <h1>首页</h1>
}

动态元数据

tsx
// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }): Promise<Metadata> {
  const post = await getPost(params.slug)
  
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      images: [post.coverImage],
    },
  }
}

🚀 Sitemap

生成 sitemap

tsx
// app/sitemap.ts
import { MetadataRoute } from 'next'

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getPosts()
  
  const postUrls = posts.map((post) => ({
    url: `https://example.com/blog/${post.slug}`,
    lastModified: post.updatedAt,
    changeFrequency: 'weekly' as const,
    priority: 0.8,
  }))
  
  return [
    {
      url: 'https://example.com',
      lastModified: new Date(),
      changeFrequency: 'daily',
      priority: 1,
    },
    {
      url: 'https://example.com/about',
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.5,
    },
    ...postUrls,
  ]
}

📝 Robots.txt

tsx
// app/robots.ts
import { MetadataRoute } from 'next'

export default function robots(): MetadataRoute.Robots {
  return {
    rules: {
      userAgent: '*',
      allow: '/',
      disallow: '/admin/',
    },
    sitemap: 'https://example.com/sitemap.xml',
  }
}

🎨 结构化数据

JSON-LD

tsx
export default function BlogPost({ post }) {
  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'Article',
    headline: post.title,
    author: {
      '@type': 'Person',
      name: post.author,
    },
    datePublished: post.publishedAt,
    image: post.coverImage,
  }
  
  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <article>{post.content}</article>
    </>
  )
}

📚 最佳实践

1. 语义化 HTML

tsx
<article>
  <header>
    <h1>文章标题</h1>
    <time dateTime="2024-01-01">2024年1月1日</time>
  </header>
  <section>
    <p>文章内容...</p>
  </section>
</article>

2. 图片 alt 属性

tsx
<Image
  src="/hero.jpg"
  alt="网站首页英雄图 - 展示产品特性"
  width={1200}
  height={600}
/>

3. 内部链接

tsx
<Link href="/blog">
  查看所有博客文章
</Link>

4. 页面加载速度

  • 使用 Image 组件优化图片
  • 启用代码分割
  • 使用 CDN
  • 压缩资源

🔗 相关资源


下一步:学习 Next.js 安全最佳实践