nginx reverse proxy disable cache

Kévin Gaulin picture Kévin Gaulin · Jan 10, 2019 · Viewed 13.5k times · Source

i use nginx as a reverse proxy to connect a api. The problem is when i send a query after add or remove something. Nginx send me the old json value. I tried to disabled cache but it's not working.

my nginx config:

location  / {

  sendfile off;
  add_header Last-Modified $date_gmt;
  add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
  if_modified_since off;
  expires off;
  etag off;
  proxy_no_cache 1;
  proxy_cache_bypass 1;

  proxy_pass http://127.0.0.1:5000;
  proxy_set_header Host $http_host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header HTTPS   $https;
}

i tried query without nginx and all work well in console

thank you!

Answer

bdzzaid picture bdzzaid · May 22, 2019

According to the documentation proxy_cache you have to replace

proxy_no_cache 1;
proxy_cache_bypass 1;

proxy_no_cache and proxy_cache_bypass defines conditions under which the response will not be saved to a cache.

Then to disable the cache, you can replace these two condition with

proxy_cache off;

Here a full exemple that you can use to configure a proxy for a stateless api server

location /myapi {

        # Proxy 
        proxy_set_header                X-Localhost true;
        proxy_set_header                X-Real-IP $remote_addr;
        proxy_set_header                X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass                      http://localhost:8080/myapi;

        proxy_redirect                  off;
        proxy_buffers                   32 16k;
        proxy_busy_buffers_size         64k;
        proxy_cache                     off;


        # Headers for client browser NOCACHE + CORS origin filter 
        add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        expires off;
        add_header    'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
        add_header    'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept' always;

        allow all;
    }