I have a REST API behind an nginx proxy. Proxying works fine, however I am unable to cache any responses. Any help would be much appreciated:
Nginx config:
worker_processes 10;
error_log logs/error.log;
error_log logs/error.log notice;
error_log logs/error.log info;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
proxy_cache_path /path/to/cache/dir keys_zone=one:60m;
proxy_cache_methods GET HEAD POST;
upstream backend {
server server1 backup;
server server2 weight=5;
}
access_log logs/access.log;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 7076;
server_name localhost;
#charset koi8-r;
access_log logs/host.access.log;
location / {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Content-Type,Accept';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
proxy_cache one;
proxy_cache_key $host$uri$is_args$args;
add_header X-Proxy-Cache $upstream_cache_status;
proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
proxy_ignore_headers Set-Cookie;
proxy_ignore_headers Cache-Control;
proxy_hide_header Cache-Control;
proxy_hide_header Set-Cookie;
proxy_pass http://backend;
}
}
}
No matter what I have tried, the Proxy-Cache always comes back as a MISS:
Request Headers are:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:nginxserver:portnumber
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
Reponse Headers are:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type,Accept
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Type:text/plain;charset=UTF-8
Date:Wed, 15 Oct 2014 16:30:18 GMT
Server:nginx/1.7.4
Transfer-Encoding:chunked
X-Proxy-Cache:MISS
My suspicion is that it's something with the client headers, but even if I issue the call via curl and check out the headers, there is no response.
Thanks in advance
Best Answer
You didn't tell NGINX for how much time the response is valid and must be served from cache.
This must be specified with
proxy_cache_valid
directive.But, this won't work for POST requests because you have no cache key that differs from a POST request to another on the same URL if they don't have same content.
So you will need to adjust the cache key to
$host$request_uri|$request_body
. You will have to monitor the cache size (proxy_cache_path
parametermax_size
) and proxy response bufferproxy_buffer_size
so it suits your needs.