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
set_if_empty
from github.com/openresty/set-misc-nginx-moduleuninitialized_variable_warn
doesn't need to be set globally, you can just set it where you need to use potentially uninitialised variables. I'm using this for passing SSL details to PHP, which will be empty if the page is accessed without SSL.nginx: [emerg] "uninitialized_variable_warn" directive is duplicate in
uninitialized_variable_warn
as part of aphp.conf
that's imported only by locations that support PHP, so I'm definitely using it only in those scopes, while leaving the warning everywhere else. I don't haveuninitialized_variable_warn
set at any other scope though (letting it default totrue
).