Nginx – How to check Cookie header line and custom cache on Nginx

nginx

I am trying cache for my website use Nginx Proxy module and has following requirements:

If request has cookie (in request header)

  • The response will use cache of Nginx
  • Hide Set-Cookie header line

If request has no cookie (in request header)

  • Foward request to backend
  • Don't hide h Set-Cookie header line

I use If (of rewrite module) and any directive:

if (!-e $http_cookie) 
{
  set $not_cache_rq 0;
  set $not_cache_rp 0;
}
if ($http_cookie) {
  set $not_cache_rq 1;
  set $not_cache_rp 1;
}
proxy_cache_bypass $not_cache_rq;
proxy_no_cache $not_cache_rp;
proxy_hide_header  Set-Cookie;

I do not know how to call cookie proxy_hide_header option when has cookie and no cookie on header line.

Please help me. Many thanks.

====

Hi poige

I manage a customer's website. If cookies are set, all request and response contain the Cookie header line.

If a response is cached. The cache will be Nginx returns for all clients and Set-Cookie header line will make all users share a cookie value (this value is the session, it must be different for each user).

I want if the user do not has a session (ie no cookie exists – request header line will not have the Cookie line), the request will be pushed into the backend (apache) for processing and returns the cookie to the user.

If the user already has session (ie a cookie in the request line) then Nginx will return the cache and the cache has no Set-Cookie line)

Many thanks!

Best Answer

If you set your proxy_cache_key to some string that contains cookie variable, than all users with different cookies will have its own cached version of page.

Like this

  proxy_cache_key  "$host$request_uri$cookie_auth_id";

This will allow both caching and distinctive pages for different users.

Related Topic