通过代理表达
在反向代理后运行 Express 应用时,一些 Express API 可能返回的值与预期不同。为了调整这一点,可以使用 trust proxy 应用设置在 Express API 中显示由反向代理提供的信息。最常见的问题是,显示客户端 IP 地址的 Express API 可能会显示反向代理的内部 IP 地址。
🌐 When running an Express app behind a reverse proxy, some of the Express APIs may return different values than expected. In order to adjust for this, the trust proxy application setting may be used to expose information provided by the reverse proxy in the Express APIs. The most common issue is express APIs that expose the client’s IP address may instead show an internal IP address of the reverse proxy.
Note
在配置 trust proxy 设置时,了解反向代理的具体设置非常重要。由于此设置会信任请求中提供的值,因此确保 Express 中的设置与反向代理的运行方式相匹配非常重要。
🌐 When configuring the trust proxy setting, it is important to understand the exact setup of the
reverse proxy. Since this setting will trust values provided in the request, it is important that
the combination of the setting in Express matches how the reverse proxy operates.
应用设置 trust proxy 可以设置为下表中列出的值之一。
🌐 The application setting trust proxy may be set to one of the values listed in the following table.
| 类型 | 值 |
|---|---|
| 布尔值 | 如果 如果 🌐 If Warning当设置为 🌐 When setting to |
| IP 地址 | 要信任为反向代理的 IP 地址、子网或 IP 地址和子网数组。以下列表显示了预配置的子网名称:
你可以通过以下任意一种方式设置IP地址: 🌐 You can set IP addresses in any of the following ways: 当指定时,IP 地址或子网会从地址确定过程中排除,并且离应用服务器最近的不受信任的 IP 地址会被确定为客户端的 IP 地址。这是通过检查 🌐 When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client’s IP address. This works by checking if |
| 编号 | 使用距离 Express 应用最多为 Warning使用此设置时,重要的是要确保不存在多个不同长度的路径通向 Express 应用,以免客户端距离配置的跳数少于预期,否则客户端可能能够提供任意值。 🌐 When using this setting, it is important to ensure there are not multiple, different-length paths to the Express application such that the client can be less than the configured number of hops away, otherwise it may be possible for the client to provide any value. |
| 功能 | 自定义信任实现。 |
启用 trust proxy 将产生以下影响:
🌐 Enabling trust proxy will have the following impact:
req.hostname 的值来源于
X-Forwarded-Host头中设置的值,该值可以由客户端或代理设置。X-Forwarded-Proto可以由反向代理设置,用于告诉应用它是https还是http,甚至是一个无效的名称。此值通过 req.protocol 反映出来。req.ip 和 req.ips 的值是根据套接字地址和
X-Forwarded-For头生成的,从第一个不受信任的地址开始。
trust proxy 设置是使用 proxy-addr 包实现的。有关更多信息,请参阅其文档。
🌐 The trust proxy setting is implemented using the proxy-addr package. For more information, see its documentation.