0

I am trying to learn caching using nginx to cache my NEXT APIs. This is my nginx.config

worker_processes 1;

events {
    worker_connections 1024;
}

http {
    proxy_cache_path /tmp/nginx/cache levels=1:2 keys_zone=portfolio:10m max_size=1g inactive=60m use_temp_path=off;

    server {
        listen 2300;
        server_name localhost;

        # Default route - no caching
        location / {
            proxy_pass http://localhost:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
        
        # API routes with caching
        location /api/ {
            proxy_pass http://localhost:3000/api/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            
            # Cache configuration
            proxy_cache portfolio;
            proxy_cache_methods GET HEAD;
            proxy_cache_key "$request_uri"; 
            proxy_cache_valid any 10m;  
            proxy_cache_lock on; 
            proxy_cache_lock_age 10s; 
            proxy_cache_lock_timeout 3s;
            add_header X-Cache-Status $upstream_cache_status;
            add_header Cache-Control "public, max-age=600";
        }
    }
}

It's caching properly and if i use curl the x-cache-status properly shows HIT after the first request but in browser although caching is working, that I can understand from the the response time and also no API call in NEXT app, the x-cache-status always shows MISS. Sometimes for some APIs it shows HIT but not consistent. How to solve it?

4
  • Can you try curl with below headers. curl -H "Cache-Control: no-cache" -H "Pragma: no-cache" -H "User-Agent: Mozilla" localhost:2300/api/your-endpoint if its behaving same as browser then add below to config and try. Set proxy_ignore_headers to ignore Cache-Control and Pragma Commented Apr 13 at 15:37
  • @Vijay i tried with those Headers and with curl it returns HIT but in browser it always shows MISS , I am using Chrome browser Commented Apr 13 at 15:56
  • in addition to the above, can you try adding the below too. proxy_hide_header Vary; Commented Apr 13 at 23:34
  • still same after adding proxy_ignore_headers Cache-Control and proxy_hide_header Vary , trying to write Pragma in proxy_ignore_headers is giving invalid value error so i skipped that Commented Apr 14 at 12:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.