<a id="redirects"></a>

# 重定向

`redirects` 模块提供了用于管理 URL 与 `Pages` 或其他 URL 之间任意重定向的模型和用户界面。

## 安装

`redirects` 模块默认不启用。要安装它，请把 `wagtail.contrib.redirects` 加入 `INSTALLED_APPS`，并把 `wagtail.contrib.redirects.middleware.RedirectMiddleware` 加入项目 Django 设置文件中的 `MIDDLEWARE`。

```python
INSTALLED_APPS = [
    # ...
    "wagtail.contrib.redirects",
]

MIDDLEWARE = [
    # ...
    # 其他所有 django 中间件放在前面
    "wagtail.contrib.redirects.middleware.RedirectMiddleware",
]
```

该应用包含迁移，所以安装后请确保运行 `migrate` 这个 django-admin 命令。

## 用法

安装后，“设置”菜单里应出现一个新的菜单项“Redirects”。你可以在这里为站点添加任意重定向。

关于面向编辑的界面指南，见我们的操作指南：[管理重定向](https://guide.wagtail.org/en/how-to-guides/manage-redirects/)。

## 自动创建重定向

当页面（及其后代页面）被移动或其 slug 被更改时，Wagtail 会自动为它们创建永久重定向。这有助于长期保持页面的 SEO 排名，也能帮助使用书签或过期链接的站点访客找到正确的位置。

### 为替代页面路由创建重定向

如果你的项目使用 `RoutablePageMixin` 创建带替代路由的页面，你可能需要考虑为这些页面类型覆盖 `get_route_paths()` 方法。把常用路由路径加入该列表会带来额外的重定向；这也能帮助走替代路由的访客找到正确的位置。

更多信息请见 [`get_route_paths()`](../models.html.md#wagtail.models.AbstractPage.get_route_paths)。

### 禁用自动创建重定向

Wagtail 的默认实现最适合中小型项目（5000 个页面或更少），且这些项目主要使用 Wagtail 内置方法来生成 URL。

生成重定向时会遵循对以下 `Page` 方法的覆盖，但在这些覆盖中使用特定页面字段会触发额外的数据库查询。

- [`get_url_parts()`](../models.html.md#wagtail.models.AbstractPage.get_url_parts)
- [`get_route_paths()`](../models.html.md#wagtail.models.AbstractPage.get_route_paths)

`WAGTAILREDIRECTS_AUTO_CREATE` 设置控制何时创建自动重定向：

- `True`（默认）：只为已发布（线上）的页面创建重定向。
- `False`：从不创建自动重定向。如果你发现该功能不适合你的项目，可以在项目设置中加入以下内容来禁用它：
  ```python
  WAGTAILREDIRECTS_AUTO_CREATE = False
  ```
- `"always"`：每当页面（或页面的后代）被移动或其 slug 被更改时就创建重定向，不论该页面是否在线。
  ```python
  WAGTAILREDIRECTS_AUTO_CREATE = "always"
  ```

## 管理命令

### `import_redirects`

```sh
./manage.py import_redirects
```

该命令从用户提供的文件中导入并创建重定向。

选项：

| 选项            | 说明                                          |
|---------------|---------------------------------------------|
| **src**       | 你要从中导入重定向的文件的路径。                            |
| **site**      | 你要把重定向保存到的**站点**。                           |
| **permanent** | 导入的重定向是否应为**永久**（True）或非永久（False）。默认是 True。 |
| **from**      | 你想用作重定向来源值的列索引。                             |
| **to**        | 你想用作重定向目标值的列索引。                             |
| **dry_run**   | 让你在不做任何改动的情况下运行一次导入。                        |
| **ask**       | 让你在创建每个重定向之前逐一检查和批准。                        |

## `Redirect` 类

### *class* wagtail.contrib.redirects.models.Redirect(id, old_path, site, is_permanent, redirect_page, redirect_page_route_path, redirect_link, automatically_created, created_at)

#### *static* add_redirect(old_path, redirect_to=None, is_permanent=True, page_route_path=None, site=None, automatically_created=False)

Create and save a Redirect instance with a single method.

* **参数:**
  * **old_path** -- the path you wish to redirect
  * **site** -- the Site (instance) the redirect is applicable to (if not all sites)
  * **redirect_to** -- a Page (instance) or path (string) where the redirect should point
  * **is_permanent** -- whether the redirect should be indicated as permanent (i.e. 301 redirect)
* **返回:**
  Redirect instance

<a id="redirects-api-endpoint"></a>

## API

你可以创建一个 API 端点，用来获取重定向，或按路径查找特定的重定向。

关于如何配置 Wagtail API，见 [Wagtail API v2 配置指南](../../advanced_topics/api/v2/configuration.html.md#api-v2-configuration)文档。

加入以下代码即可添加重定向端点：

```python
from wagtail.contrib.redirects.api import RedirectsAPIViewSet

api_router.register_endpoint("redirects", RedirectsAPIViewSet)
```

按此配置，重定向将在 `/api/v2/redirects/` 可用。

可以按路径解析特定重定向：`/api/v2/redirects/find/?html_path=<path>`，
它会返回带重定向详情的 `200` 响应，或 `404` 未找到响应。
