How to get original Host header when proxying request

Hi,

We are in the process of migrating our single-page app to Netlify. We have a REST API in our servers, so we are going to serve our frontend as static files from Netlify and proxy the /api directory to our API in other domain.

That is working fine, but we need our API to know the original Host header, since we are deploying our frontend in several domains and customizing some of the responses depending on the host that makes the request, but the netlify redirect substitutes the original Host header with the host of the API, so this information is lost.

Is there any way to get the original host to our API server through redirects? It would be enough to be able to append this information to every request that goes through the proxy as a custom header or get parameter, but we haven’t been able to do so.

Any advice would be greatly appreciated!

Taking another look at the request made by the Netlify proxy, we have seen that it adds a referer header with the original host. Is this a good way to have this information? Should we rely on the value of this header?

Thanks!

Hi @adrm!

You should not rely on that information. We don’t AUTOMATICALLY provide it in any reliable way even if you happen to find it working today in X-Forwarded-For or Referer. The Referer header is I think from the visitor’s browser anyway (and is also the location of the page that linked to the proxy’d URL, AFAIK - so it might change based on where people link to your site from!), and is not from Netlify’s servers.

You’d need to set some specific header that shows the name which your API can examine and use. This would be set at BUILD time for use later, by using the headers configuration attribute in your netlify.toml specified proxy rules. At a guess you could use this with your setup by creating several different /api redirects: /api-host1/*, /api-host2/*`, for which you set different headers. More docs on the topic:

You’d want something like this:

[[redirects]]
  from = "/api-host1/*"
  to = "https://remotehost/api/:splat"
  status = 200
  headers = {X-Netlify-Hostname: "host1.com"}
[[redirects]]
  from = "/api-host2/*"
  to = "https://remotehost/api/:splat"
  status = 200
  headers = {X-Netlify-Hostname: "host2.com"}
2 Likes