我在我的静态内容以及Last-Modified标题上添加了X-Accel-Expires标题。 我想知道什么是正确的设置来caching这些元素而不caching其他任何东西。
这是我目前所拥有的,但不会caching任何内容:
http { include /etc/nginx/mime.types; access_log /var/log/nginx/access.log; sendfile on; client_max_body_size 2000m; keepalive_timeout 65; tcp_nodelay on; gzip on; gzip_disable "MSIE [1-6]\.(?!.*SV1)"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; ssl_certificate /etc/nginx/chain.pem; ssl_certificate_key /etc/nginx/key.key; proxy_cache_path /var/lib/nginx/cache levels=1:2 keys_zone=cache:30m max_size=1G; proxy_temp_path /var/lib/nginx/proxy 1 2; proxy_cache_use_stale error timeout invalid_header http_502; server { listen 80; server_name domain; location / { proxy_pass http://127.0.0.1:8080; proxy_set_header X-Real-IP $remote_addr; proxy_read_timeout 700; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
要caching内容,首先需要在http
上下文中创build代理cachingpath ,如下所示:
proxy_cache_path /var/cache/nginx/site1 levels=1:2 keys_zone=site1:10m max_size=1G;
然后,您还可以select定义代理caching密钥 。 任何具有与高速caching条目相同的高速caching键的请求将接收高速caching的答复,如果有的话。 但是默认可能已经足够好了,所以这完全是可选的。
然后,要在给定的上下文中启用caching,只需提及应该使用哪个caching,如下所示:
proxy_cache site1;
根据代理caching有效指令的描述,nginx已经尊重了X-Accel-Expires
并对其执行了操作,所以,现在基本上已经完成了。 由于您不想caching任何不包含X-Accel-Expires
,因此您可能希望添加0作为默认有效时间(在您的内容中设置X-Accel-Expires
应覆盖此默认值)。
proxy_cache_valid 0m;
我会假设,除了没有任何caching,你的configuration文件是有效的,你的代理本身已经工作。
然后,基本上,所有你需要做的解决你的configuration是添加到您的http
, server
或location
上下文:
proxy_cache cache; proxy_cache_valid 0m;
(另外,您可能需要确保cachingpath存在并具有正确的权限,当然。)
关于提到的habrahabr文章/例子,我不认为在caching键中包含$http_if_modified_since
实际上是不正确的,因为你可能最终得到大量的多caching条目,从而浪费了你的caching。
另外请注意,nginx可能不会代理X-Accel-Expires
标题 – 它只在内部使用,而IIRC可能不会向前传递这个标题。 为了改变这种行为,你必须明确要求它被代理(如果你想通过nginxdebugging你的内容,并看看你的应用程序如何设置标题等):
proxy_pass_header "X-Accel-Expires";
在俄罗斯IT博客上,nginx使用X-Accel-Expires
标题是一个很好的方法。 我想,这可能对你的情况非常有用。
我认为原因是caching已定义,但未启用 – proxy_cache cache;
不见了。