6

Case: I have REST API via HTTPS and I want to configure a basic caching proxy service on my host to cache API requests and get the same information faster, as usual.

I have the following configuration of Nginx:

proxy_cache_path /tmp/cache levels=1:2 keys_zone=my_cache:10m max_size=10g
                 inactive=60m use_temp_path=off;
http {
    server {
        location /my_api/ {
            proxy_redirect off;
            proxy_buffering on;

            proxy_ignore_headers X-Accel-Expires;
            proxy_ignore_headers Expires;
            proxy_ignore_headers Cache-Control;

            proxy_cache my_cache;

            proxy_pass https://example.com/myapi/;
        }
    }
}

And now I'm comparing the response time from REST API and my local proxy service, and it is the same for the REST API call to the remote service and to my local proxy service with caching, so, it means that caching doesn't work. Also, the cache directory is empty.

The example or request to the real API (this is not the real case):

    curl "https://example.com/myapi/?key=1"

Example of request to proxy:

    curl "http://127.0.0.1:8080/myapi/?key=1"

In REST API headers I can see

cache-control: max-age=0, no-cache, no-store, must-revalidate

can Nginx ignore it somehow?

What should I change in the proxy configuration to see the boost for REST API? I wonder if the issue can be related to HTTPS traffic? Or maybe the response from REST API has some NoChaching headers or the size of the response is too small for caching?

Timur Nurlygayanov
  • 1,095
  • 2
  • 11
  • 24
  • The same questions without answers https://stackoverflow.com/questions/47239499/nginx-caching-for-rest-api https://stackoverflow.com/questions/43915693/nginx-caching-for-https – Timur Nurlygayanov Jun 23 '20 at 09:22

2 Answers2

5

Finally found the way to configure caching for my REST API, here is the final configuration:

http {
    proxy_cache_path /tmp/cache levels=1:2 keys_zone=my_cache:10m;

    server {
        listen       8080;
        server_name  localhost;

        location /myapi {
            proxy_buffering on;

            proxy_ignore_headers Expires Cache-Control X-Accel-Expires;
            proxy_ignore_headers Set-Cookie;

            proxy_cache my_cache;
            proxy_cache_valid 24h;
            proxy_pass https://example.com/myapi;
    }

}
Timur Nurlygayanov
  • 1,095
  • 2
  • 11
  • 24
  • 1
    Your REST-API should probably generate the correct cache-control headers to begin with. Caching can than safely be done by all intermediates between server and client. – Patrick Savalle Feb 04 '22 at 11:48
0

In addition, if you are caching a REST api (e.g. GET and POST), I also suggest to add proxy_cache_methods GET POST;

citti
  • 1