Score:1

Modify the `Host` header or pass `X-Forwarded-Host` instead when using Nginx as reverse proxy?

pl flag

I'm trying to use Nginx as a reverse proxy and the upstream server is an ASP.NET Core application where I've registered the ForwardedHeadersMiddleware, which will read three different X-Forwarded-* headers:

  • X-Forwarded-For
  • X-Forwarded-Proto
  • X-Forwarded-Host

Now, I understand the first two, but find the last one (X-Forwarded-Host) confusing. I've seen Nginx reverse proxy configurations usually rewriting the Host header like so:

location / {
    proxy_pass http://app;
    proxy_set_header Host $host;
}

But then I've also seen the X-Forwarded-Host being used instead:

location / {
    proxy_pass http://app;
    proxy_set_header X-Forwarded-Host $host;
}

In some cases both are used at the same time:

location / {
    proxy_pass http://app;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Host $host;
}

I'm not sure what I should do. Why would you use both at the same time? And why would anyone use the X-Forwarded-Host header if they can simply change the Host header directly? I've noticed that the result in my ASP.NET Core app will be the same regardless of whether I set Host or X-Forwarded-Host (or both), in either case, HttpContext.Request.Host is set to the expected value — provided that the forwarded headers middleware is registered, of course.

To my surprise, I couldn't find any relevant information on this issue by googling, so I had to ask this here. What is the right approach to take in this situation?

Lex Li avatar
vn flag
https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/ "Traditionally, an HTTP reverse proxy uses non-standard headers to inform the upstream server about the user’s IP address and other request properties" is the history background on server side. `HttpContext.Request.Host` works in all cases, because Microsoft tried to keep compatibility for all typical cases. You can refer to the actual ASP.NET Core source code to learn more.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.