代理背后的 Express

¥Express behind proxies

在反向代理后面运行 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.

配置 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.

类型
布尔值

如果是 true,则客户端的 IP 地址被理解为 X-Forwarded-For 标头中最左侧的条目。

如果是 false,则应用理解为直接面向客户端,客户端的 IP 地址来源于 req.socket.remoteAddress。这是默认设置。

设置为 true 时,请务必确保最后一个受信任的反向代理正在删除/覆盖以下所有 HTTP 标头:X-Forwarded-ForX-Forwarded-HostX-Forwarded-Proto,否则客户端可以提供任何值。

IP 地址

可信任作为反向代理的 IP 地址、子网或 IP 地址和子网数组。以下列表显示了预配置的子网名称:

  • loopback - 127.0.0.1/8, ::1/128

  • linklocal - 169.254.0.0/16, fe80::/10

  • uniquelocal - 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7

你可以通过以下任一方式设置 IP 地址:

app.set('trust proxy', 'loopback') // specify a single subnet
app.set('trust proxy', 'loopback, 123.123.123.123') // specify a subnet and an address
app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple subnets as CSV
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array

指定时,IP 地址或子网将被排除在地址确定过程之外,并将离应用服务器最近的不受信任的 IP 地址确定为客户端的 IP 地址。这通过检查 req.socket.remoteAddress 是否受信任来工作。如果是这样,则从右到左检查 X-Forwarded-For 中的每个地址,直到第一个不受信任的地址。

数字

使用距 Express 应用最多 n 跳数的地址。req.socket.remoteAddress 是第一跳,其余的在 X-Forwarded-For 标头中从右到左查找。值 0 意味着第一个不受信任的地址是 req.socket.remoteAddress,即没有反向代理。

使用此设置时,重要的是要确保不存在通往 Express 应用的多个不同长度的路径,以便客户端可以少于配置的跳数,否则客户端可能会提供任何值 。

函数

自定义信任实现。

app.set('trust proxy', (ip) => {
  if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs
  else return false
})

启用 trust proxy 将产生以下影响:

¥Enabling trust proxy will have the following impact: