# 服务器配置

> Source: https://strapi.nodejs.cn/cms/configurations/server

🌐 Server configuration

`/config/server` 管理主机、端口、URL、代理、定时任务等；更改需要重新构建管理面板。

`/config/server.js` 文件用于定义 Strapi 应用的服务器配置。

🌐 The `/config/server.js` file is used to define the server configuration for a Strapi application.

:::caution

对 `server.js` 文件的更改需要重建管理面板。保存修改后的文件后，在终端中运行 `yarn build` 或 `npm run build` 以实现更改。

🌐 Changes to the `server.js` file require rebuilding the admin panel. After saving the modified file run either `yarn build` or `npm run build` in the terminal to implement the changes.

:::

## 可用选项 {#available-options}

🌐 Available options

`/config/server.js` 文件可以包含以下参数：

🌐 The `/config/server.js` file can include the following parameters:

| 参数 | 描述 | 类型 | 默认 |
| --- | --- | --- | --- |
| `host`<br/><br/>❗️ _必填_ | 主机名 | 字符串 | `localhost` |
| `port`<br/><br/>❗️ _必填_ | 服务器应运行的端口。 | 整数 | `1337` |
| `app.keys`<br/><br/>❗️ _必填_ | 声明会话密钥（基于 [Koa session](https://github.com/koajs/session/blob/master/Readme.md)），用于 `session` 中间件的用户与权限插件以及文档插件。 | 字符串数组 | `undefined` |
|“socket” |用插座听。当提供这个选项时，主机和端口只是装饰性，使用时也请使用“url”来生成正确的URL。该选项适用于运行服务器时不暴露端口，同时在同一台机器上使用代理服务器（例如  [Heroku nginx buildpack](https://github.com/heroku/heroku-buildpack-nginx#requirements-proxy-mode)| 字符串 \| 整数 | '/tmp/nginx.socket' |
| `emitErrors` | 当发生错误时，启用将错误发送到 `koa`，以便附加自定义逻辑或使用错误报告服务。 | 布尔值 | `false` |
| `url` | 服务器的公共网址。许多不同功能需要此项（例如：重置密码、第三方登录提供商等）。同时支持代理，如 Apache 或 Nginx，示例：`https://mywebsite.com/api`。网址可以是相对的，如果是相对的，将与 `http://${host}:${port}` 一起作为基础网址使用。不过，推荐使用绝对网址。 | 字符串 | `''` |
| `proxy` | 代理配置 | 对象 | |
| `proxy.global` | 定义所有外部请求的代理代理。如果 Strapi 项目位于前置代理之后，则使用此选项。 | 字符串 | |
|“proxy.fetch” |所有在“strapi.fetch”内请求的代理（用于许可检查、遥测和webhook）|字符串 \| [ProxyAgent.Options](https://github.com/nodejs/undici/blob/main/types/proxy-agent.d.ts) | |
| `proxy.http` | 所有（非 fetch）HTTP 请求的代理 | 字符串 | |
| `proxy.https` | 所有（非 fetch）https 请求的代理 | 字符串 | |
| `proxy.koa` | 设置 koa 变量 `app.proxy`。当 `true` 时，代理头字段将被信任。 | 布尔值 | `false` |
| `cron` | Cron 配置（由 [`node-schedule`](https://github.com/node-schedule/node-schedule) 提供支持） | 对象 | |
| `cron.enabled` | 启用或禁用 [CRON 作业](/cms/configurations/cron.md) 以在特定日期安排作业。 | 布尔值 | `false` |
| `cron.tasks` | 声明将在特定日期运行的 [CRON 作业](/cms/configurations/cron.md)。 | 对象 | |
| `dirs` | Strapi 使用的不同目录的路径配置。 | 对象 | |
| `dirs.public` | 自定义公共文件夹的路径。 | 字符串 | `./public` |
| `http` | Strapi 使用的 HTTP 服务器配置 | 对象 | |
| `http.serverOptions` | 传递给 http `createServer` 的选项 | [http.serverOptions](https://nodejs.cn/api/http.html#httpcreateserveroptions-requestlistener) | {} |
| `transfer.remote.enabled` | 切换使用 [传输功能](/cms/data-management/transfer) 的能力 | 布尔值 | `true` |
| `transfer.remote.assetIdleTimeoutMs` | 在使用 `strapi transfer --from` 从远程实例拉取时，如果在指定毫秒数内没有收到数据，则认为资源流已停止。当传输大文件或在慢速连接上工作时，请增加此值。 | 整数 | |
| `webhooks.populateRelations` | 当 `true` 时，关系字段会包含在 webhook 事件负载中。设置为 `false` 可以保持负载轻量，并避免在传出的 webhook 请求中暴露关系数据。 | 布尔值 | `true` | | 布尔值 | `true` |
| `logger.startup.enabled` | 切换终端启动消息 | 布尔值 | `true` |
| `logger.updates.enabled` | 切换终端中关于更新 strapi 的通知消息 | 布尔值 | `true` |
| `openapi` | [OpenAPI](/cms/api/openapi) 端点配置。两个端点默认都使用 `access: 'disabled'`，且未注册。 | 对象 | |
| `openapi['content-api'].access` | 访问模式：`disabled`（未注册）或 `public`（无认证）。| 字符串 | `disabled` |
| `openapi['content-api'].route.path` | 内容 API 端点的子路径，在 [REST API 前缀](/cms/configurations/api) 下解析。 | string | `/openapi.json` |
| `openapi['content-api'].cache.enabled` | 启用基于文件的生成规范缓存。 | 布尔值 | `true` |
| `openapi['content-api'].cache.maxAgeMs` | 缓存有效时间（毫秒）。 | 整数 | `60000` |
| `openapi['content-api'].cache.filePath` | 缓存规范的文件路径。相对路径从应用根目录解析。 | 字符串 | `.strapi/openapi/content-api.json` |
| `openapi.admin.access` | 访问模式：`disabled`（未注册）或 `authenticated`（需要管理员会话）。 | 字符串 | `disabled` |
| `openapi.admin.route.path` | 管理端点的子路径，在 [admin path](/cms/configurations/admin-panel) 下解析。 | string | `/openapi.json` |
| `openapi.admin.cache.enabled` | 启用对生成的规范进行基于文件的缓存。 | 布尔值 | `true` |
| `openapi.admin.cache.maxAgeMs` | 缓存有效时间（毫秒）。 | 整数 | `60000` |
| `openapi.admin.cache.filePath` | 缓存规范的文件路径。相对路径从应用根目录解析。 | 字符串 | `.strapi/openapi/admin.json` |

:::note

没有特定于 Strapi 的保持活动配置选项，因为 Strapi 使用 Node 的默认选项来处理传入的 HTTP 请求，默认情况下保持连接活动。 

🌐 There is no Strapi-specific keep alive configuration option, because Strapi uses Node's default one for incoming HTTP requests, keeping connections alive by default. 

对于外发的 HTTP 调用，你可以将一个保持连接的代理传递给你的 HTTP 客户端。使用 [`agentkeepalive`](https://github.com/node-modules/agentkeepalive) 和 Axios 的示例：

🌐 For outgoing HTTP calls, you can pass a keep-alive agent to your HTTP client.
Example with [`agentkeepalive`](https://github.com/node-modules/agentkeepalive) and Axios:

```js
const { HttpsAgent } = require('agentkeepalive');
const axios = require('axios');

const agent = new HttpsAgent();
axios.get('https://example.com', { httpsAgent: agent });
```

:::

:::tip

Strapi 提供了一个专用的健康检查路由用于运行时间探测。对 `/_health` 的任何请求都会返回一个空响应，并带有 `204` 状态和 `strapi: You are so French!` 响应头，这适用于只需要简单存活指示器的负载均衡器或监控工具。

🌐 Strapi exposes a dedicated health check route for uptime probes. Any request to `/_health` returns an empty response with a `204` status and a `strapi: You are so French!` response header, which is suitable for load balancers or monitoring tools that only need a simple liveness indicator.

:::

## 配置 {#configurations}

🌐 Configurations

`/config/server.js`最小配置在开发时需要`host`和`port`参数。完整配置可以包括更多参数。

🌐 The `/config/server.js` minimal configuration requires the `host` and `port` parameters for development. Additional parameters can be included for a full configuration.

:::note

[环境配置](/cms/configurations/environment.md)（即使用 `env()` 助手）不需要包含所有值，只要它们存在于默认的 `./config/server.js` 中即可。

:::

使用任何新项目创建的默认配置至少应包括以下内容：
```js title="./config/server.js"
module.exports = ({ env }) => ({
  host: env('HOST', '0.0.0.0'),
  port: env.int('PORT', 1337),
  app: {
    keys: env.array('APP_KEYS'),
  },
});
```

```ts title="./config/server.ts"

  host: env('HOST', '0.0.0.0'),
  port: env.int('PORT', 1337),
  app: {
    keys: env.array('APP_KEYS'),
  },
});
```

 以下是一个完整配置文件的示例。并非所有这些键都是必需的（请参见 [可用选项](#available-options)）。

🌐 The following is an example of a full configuration file. Not all of these keys are required (see [available options](#available-options)).

```js title="./config/server.js"
module.exports = ({ env }) => ({
  host: env('HOST', '0.0.0.0'),
  port: env.int('PORT', 1337),
  app: {
    keys: env.array('APP_KEYS'),
  },
  socket: '/tmp/nginx.socket', // only use if absolutely required
  emitErrors: false,
  url: env('PUBLIC_URL', 'https://api.example.com'),
  proxy: { koa: env.bool('IS_PROXIED', true) },
  cron: {
    enabled: env.bool('CRON_ENABLED', false),
  },
  transfer: {
    remote: {
      enabled: false,
    },
  },
  webhooks: {
    populateRelations: false,
  },
  logger: {
    updates: {
      enabled: false,
    },
    startup: {
      enabled: false,
    },
  },
  // highlight-start
  openapi: {
    'content-api': {
      access: 'public',
    },
  },
  // highlight-end
});
```

```js title="./config/server.ts"

  host: env('HOST', '0.0.0.0'),
  port: env.int('PORT', 1337),
  app: {
    keys: env.array('APP_KEYS'),
  },
  socket: '/tmp/nginx.socket', // only use if absolutely required
  emitErrors: false,
  url: env('PUBLIC_URL', 'https://api.example.com'),
  proxy: { koa: env.bool('IS_PROXIED', true) },
  cron: {
    enabled: env.bool('CRON_ENABLED', false),
  },
  transfer: {
    remote: {
      enabled: false,
    },
  },
  webhooks: {
    populateRelations: false,
  },
  logger: {
    updates: {
      enabled: false,
    },
    startup: {
      enabled: false,
    },
  },
  // highlight-start
  openapi: {
    'content-api': {
      access: 'public',
    },
  },
  // highlight-end
});
```
