Nginx $cookie variable and dashes

I was configuring a Nginx proxy server for a big dynamic website. To lower the load I decided to cache all public accessible HTML and bypass the proxy when a user was logged in to the forums or the website itself.

Thats pretty easy, all you have to do is:

proxy_no_cache $cookie_user$cookie_name$cookie_others;  
proxy_cache_bypass $cookie_user$cookie_name$cookie_others;  
proxy_cache_key $scheme$proxy_host$uri$is_args$args;  

But it didn't work. Every single time my requests were bypassing the cache and hitting the backend directly. It took me a while to figure it out so I wanted to save people some time.

The problem was in the forum's cookie name. It contained a dash forum-login but Nginx was cutting the variable at the dash symbol and treating -login as a separate value. Since that value is present 100% of the times the cache was never used.

Turns out Nginx automatically converts all dashes in cookies to lower underscore forum_login.
So the final config looked something like this:

proxy_no_cache $cookie_user$cookie_Forum$cookie_Forum_login;  
proxy_cache_bypass $cookie_user$cookie_Forum$cookie_Forum_login;  
proxy_cache_key $scheme$proxy_host$uri$is_args$args;  

It immediately shaved 60% of the load on the backend server and improved the overall performance.

comments powered by Disqus