> For AI agents: the complete documentation index is available at https://rspress.rs/zh/llms.txt, the full documentation bundle is available at https://rspress.rs/zh/llms-full.txt.

# @rspress/plugin-client-redirects 

[源码](https://github.com/web-infra-dev/rspress/tree/main/packages/plugin-client-redirects)

用于客户端重定向。

:::warning
使用此插件前，请先确保部署环境已正确配置 fallback 页面，详见 [刷新 404（fallback 配置）](https://rspress.rs/zh/guide/basic/ssg.md#refresh-404)。

注意：客户端重定向与服务端重定向不同，页面会先加载再跳转（会有一次闪屏），且不支持 SSR。如果你的部署平台支持配置服务端重定向（301/302），建议优先使用服务端方案，以获得更好的 SEO 和用户体验。
:::

## 安装


```sh [npm]
npm add @rspress/plugin-client-redirects -D
```

```sh [yarn]
yarn add @rspress/plugin-client-redirects -D
```

```sh [pnpm]
pnpm add @rspress/plugin-client-redirects -D
```

```sh [bun]
bun add @rspress/plugin-client-redirects -D
```

```sh [deno]
deno add npm:@rspress/plugin-client-redirects -D
```

## 使用

在配置文件中写入以下的配置：

```ts title="rspress.config.ts"
import { pluginClientRedirects } from '@rspress/plugin-client-redirects';
import { defineConfig } from '@rspress/core';

export default defineConfig({
  plugins: [
    pluginClientRedirects({
      redirects: [
        {
          from: '/docs/old1',
          to: '/docs/new1',
        },
      ],
    }),
  ],
});
```

## 配置

该插件支持传入一个对象配置，该对象配置的属性如下：

```ts
type RedirectRule = {
  from: string | string[];
  to: string;
};

type RedirectsOptions = {
  redirects?: RedirectRule[];
};
```

`from` 表示匹配的路径，`to` 表示要重定向的路径，支持传入正则表达式字符串。

:::note

一个 `to` 支持匹配多个 `from`：它们将重定向到一个路径。

一个 `from` 不能对应多个 `to`：需要有一个唯一明确的重定向路径。

:::

## 示例

```ts
import path from 'node:path';
import { defineConfig } from '@rspress/core';
import { pluginClientRedirects } from '@rspress/plugin-client-redirects';

export default defineConfig({
  root: path.join(__dirname, 'doc'),
  plugins: [
    pluginClientRedirects({
      redirects: [
        // /docs/old1 -> /docs/new1
        {
          from: '/docs/old1',
          to: '/docs/new1',
        },
        // redirect from multiple old paths to the new path
        {
          from: ['/docs/2022', '/docs/2023'],
          to: '/docs/2024',
        },
        // redirect using regular expressions
        {
          from: '^/docs/old2',
          to: '/docs/new2',
        },
        {
          from: '/docs/old3$',
          to: '/docs/new3',
        },
        // redirect to an external URL
        {
          from: '/docs/old4',
          to: 'https://example.com',
        },
      ],
    }),
  ],
});
```
