50

I've been reading up on reverse proxying and am wondering when proxy_set_header Host $host is appropriate over proxy_set_header Host $proxy_host. I did some research and in this article it says that in most cases we set Host to $host. Then why does nginx default to $proxy_host? To help me understand more concretely, will the reverse proxy configuration here (bottom of article) still work if we use $proxy_host instead?

Thanks

2 Answers 2

53

In general there is no need to explicitly do proxy_set_header Host $proxy_host because it's the default. If you need to call a server by something other than what is in the proxy_pass directive, then you will need to override via proxy_set_header something.

If you want to proxy the same host as was in your server_name directive, then you would have occasion to use proxy_set_header $host. This would commonly be the case if perhaps the actual application is hosted on another port or on some internal server.

server {
    listen 80;
    server_name site.example.com;
    
    location / {
       proxy_set_header Host $host;
       proxy_pass http://localhost:8080;
    }
}

If the name you are calling the upstream is not its actual DNS name, then you might have something like:

# 192.168.2.1 responds to site.example.com, but
# site.example.com doesn't actually resolve to 192.168.2.1
proxy_pass http://192.168.2.1;
proxy_set_header Host site.example.com;

Another case might be for "name-based" virtual hosting where there is a useful DNS name for the upstream, but you would like to call it by another name.

proxy_pass http://origin.example.com;
proxy_set_header Host site.example.com
3
  • 1
    Does the order of proxy_pass and proxy_set_header matter?
    – iBug
    Commented Jun 14, 2019 at 17:05
  • 2
    @iBug Nope! the upstream module will read each of the settings applicable for its internal phases, and then apply the when it issues the actual proxy_pass. You'll get the exact same behavior if the proxy_set_header is after proxy_pass in the config. Commented Jun 16, 2019 at 5:16
  • 6
    I am having a difficult time understanding the wording of the definitions of $hostand $proxy_host. So is this wrong: A client sends a request to an nginx server A which proxy passes it to backend B. Then $host would be the url of A, while $proxy_host would be the url of B. So if I want future requests of the client to still be directed at A, I would want to use $host? Is that correct?
    – Felix B.
    Commented May 1, 2021 at 16:06
1

$proxy_host is a tag about upstreams servers, so nginx do this one by default.

If you want to add other tag(header) about the host, use $host.

Not the answer you're looking for? Browse other questions tagged or ask your own question.