How to Use Custom HTTP Headers as Nginx Variables

Are you aware that the HTTP headers that appear in requests to an nginx server double as variables?

In order to form an nginx variable, nginx converts HTTP headers to lower case, converts dashes to underscores, and adds $http_.

Let’s look at two examples.

The header typically created by proxies to identify the originating IP address is HTTP-X-FORWARDED-FOR; if you’d like to use this value in an nginx config file, it’s accessible as $http_x_forwarded_for.

In the case where a header doesn’t begin with “HTTP-“, it’s added. So the header ACCEPT-LANGUAGE becomes $http_accept_language.

Using the above variables, you can extend your nginx server’s logging capabilities to capture additional information or make more granular programmatic decisions in nginx config files.

If you’re interested in seeing a list of nginx variables, check out this article.