NGiNX Custom Cache param based on regex match

cachehttp-headersnginxreverse-proxyuseragent

My question(s) are as follows:

  • How do I set custom variables based on regexp against a useragent?
  • How do I set custom headers for the reverse-proxy request?
  • How do I use these values as caching parameters?

Details:

I'm doing an initial output in my application based on user-agent parsing… which basically breaks down request rendering so the initial rendering will match the bootstrap sizes of "xs","sm","md","lg" …

I have my regular expressions worked out so that mobile devices will get output rendered for "xs" and common tablets will get "sm" by default, anyone else gets "md" … after the client-side binding, it will adjust to the actual device display, this is mainly so that browsers will get the size that they need.

What I want to be able to do is:

  • based on a pattern match against the user-agent set a few parameters, that will be passed through (reverse-proxy) to my application
    • X-Initial-Size – "xs", "sm", "md", "lg" (realistically nothing will resolve to "lg"
    • X-Is-Human – match against known bots for detection
    • X-Browser-Class – "ancient", "modern", "ie#" (IE <= 9 only)
  • use X-Initial-Size and X-Browser-Class as vary-by params for longer-lived server-side output caching.

Best Answer

- How do I set custom variables based on regexp against a useragent?

Use a map. For instance :

map $http_user_agent $my_var {
    default     "default_value";
    "~^foo$"    "value_1";
    "~^bar$"    "value_2";
}

- How do I set custom headers for the reverse-proxy request?

Use proxy_set_header. For example :

proxy_set_header My-Header $my_var;

- How do I use these values as caching parameters?

Define these additional headers as part of your proxy cache key :

proxy_cache_key $scheme$request_uri-$http_my_header-$http_my_other_header