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.
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.
The application setting trust proxy
may be set to one of the values listed in the following table.
Type | Value |
---|---|
Boolean | If If When setting to |
IP addresses | An IP address, subnet, or an array of IP addresses and subnets to trust as being a reverse proxy. The following list shows the pre-configured subnet names:
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. This works by checking if |
Number | Use the address that is at most 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. |
Function | Custom trust implementation. app.set('trust proxy', (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 based on the socket address and X-Forwarded-For
header, starting at the first untrusted address.
The trust proxy
setting is implemented using the proxy-addr package. For more information, see its documentation.
© 2017 StrongLoop, IBM, and other expressjs.com contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v3.0.
https://expressjs.com/en/guide/behind-proxies.html