I think the simple answer is that you ought to use a map
, but none of the answers here or in similar questions were an approach that worked for my usage in the latest Nginx versions, so for those situations the below seems to work.
In my case I needed to overwrite the Host header, conditionally, in an included general configuration file shared by many sites, whilst only setting that for the sites that needed it.
In this case, in your http
block (e.g. nginx.conf
):
map '' $proxied_host {
default '';
}
map "$proxied_host" $resolved_host {
default $host;
~. $proxied_host;
}
and in the included configuration file in every location:
proxy_set_header Host $resolved_host:$server_port;
then in the sites that need to overwrite it, in the location block:
set $proxied_host your.example.com;
This is the only way I found to avoid:
- Floods of warnings in error.log saying
using uninitialized "proxied_host" variable
- Errors related to using uninitialized variables in the map like
nginx: [emerg] unknown "proxied_host" variable
- Errors relating to cycles in variables
cycle while evaluating variable "proxied_host"
These last two errors appeared when following the answers in this question