返回介绍

为 Express 设置代理

发布于 2020-12-20 08:19:48 字数 3485 浏览 1377 评论 0 收藏 0

When running an Express app behind a proxy, set (by using app.set()) the application variable trust proxy to one of the values listed in the following table.

Although the app will not fail to run if the application variable trust proxy is not set, it will incorrectly register the proxy’s IP address as the client IP address unless trust proxy is configured.

TypeValue
Boolean

If true, the client’s IP address is understood as the left-most entry in the X-Forwarded-* header.

If false, the app is understood as directly facing the Internet and the client’s IP address is derived from req.connection.remoteAddress. This is the default setting.

IP addresses

An IP address, subnet, or an array of IP addresses and subnets to trust. The following list shows the pre-configured subnet names:

  • 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

You can set IP addresses in any of the following ways:

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

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.

Number

Trust the nth hop from the front-facing proxy server as the client.

Function

Custom trust implementation. Use this only if you know what you are doing.

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

Enabling trust proxy will have the following impact:

  • The value of req.hostname is derived from the value set in the X-Forwarded-Host header, which can be set by the client or by the proxy.

  • X-Forwarded-Proto can be set by the reverse proxy to tell the app whether it is https or http or even an invalid name. This value is reflected by req.protocol.

  • The req.ip and req.ips values are populated with the list of addresses from X-Forwarded-For.

The trust proxy setting is implemented using the proxy-addr package. For more information, see its documentation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文