Better way to forward port/proto in NGINX?

An NGINX server may be running behind another “forwarder” e.g. a WAF, or it may be running standalone. I want to use the same configuration either way, so I set up a couple maps which are used to set the X-Forwarded-* headers:

    # Uses the forwarded protocol/scheme if one exists.
    map $http_x_forwarded_proto $which_proto {
        http http;
        https https;
        default $scheme;
    }

    # Uses the forwarded port if one exists.
    map $http_x_forwarded_port $which_port {
        80 80;
        443 443;
        default $server_port;
    }

The maps are used like this:

proxy_set_header X-Forwarded-Proto  $which_proto;
proxy_set_header X-Forwarded-Port   $which_port;

Is there a better way to set the headers to use the incoming header if there is one, else use the built-in $scheme / $server_port variables?

Read more here: Source link