MST
星途 面试题库

面试题:Next.js动态路由在多语言SEO优化中的应用

在使用Next.js动态路由搭建多语言网站时,搜索引擎优化(SEO)至关重要。请阐述如何通过动态路由设置,使得不同语言版本的页面都能满足SEO要求,例如正确设置meta标签、URL结构优化等方面,并举例说明关键代码实现。
25.5万 热度难度
前端开发Next.js

知识考点

AI 面试

面试题答案

一键面试

1. 正确设置meta标签

在Next.js中,可以利用next/head组件来设置页面的meta标签。对于多语言网站,根据不同语言版本动态设置meta标签内容。

假设在pages/post/[id].js页面,有不同语言的文章标题和描述,可如下实现:

import Head from 'next/head';
import { useRouter } from 'next/router';

export default function Post() {
  const router = useRouter();
  const { id } = router.query;
  const { locale } = router;

  let title, description;
  if (locale === 'en') {
    title = 'English Article Title';
    description = 'English article description';
  } else if (locale === 'zh') {
    title = '中文文章标题';
    description = '中文文章描述';
  }

  return (
    <>
      <Head>
        <title>{title}</title>
        <meta name="description" content={description} />
      </Head>
      <h1>{title}</h1>
      <p>{description}</p>
    </>
  );
}

2. URL结构优化

为了满足SEO要求,URL结构应简洁且包含语言信息。在Next.js中可以通过自定义路由规则来实现。

例如,在next.config.js中配置:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/:locale/post/:id',
        destination: '/post/[id]'
      }
    ];
  }
};

这样,通过/:locale/post/:id这种URL结构,既能区分不同语言版本,又能被搜索引擎友好识别。比如/en/post/123表示英文版本的文章123/zh/post/123表示中文版本的文章123

3. 示例完整代码

假设项目目录结构如下:

pages
├── post
│   └── [id].js
└── index.js
next.config.js

pages/post/[id].js完整代码:

import Head from 'next/head';
import { useRouter } from 'next/router';

export default function Post() {
  const router = useRouter();
  const { id } = router.query;
  const { locale } = router;

  let title, description;
  if (locale === 'en') {
    title = 'English Article Title';
    description = 'English article description';
  } else if (locale === 'zh') {
    title = '中文文章标题';
    description = '中文文章描述';
  }

  return (
    <>
      <Head>
        <title>{title}</title>
        <meta name="description" content={description} />
      </Head>
      <h1>{title}</h1>
      <p>{description}</p>
    </>
  );
}

next.config.js代码:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/:locale/post/:id',
        destination: '/post/[id]'
      }
    ];
  }
};

通过上述设置,不同语言版本的页面在meta标签设置和URL结构方面都能较好地满足SEO要求。