用NGINX绕过单一IP的caching

我想设置NGINX将caching中的内容提供给每个人,但只有一个IP地址。

我想实现的2个目标是:

  1. 请确保从指定的IP我从来没有击中caching,但将被送达磁盘上的实际文件(所以如果我删除该文件,它应该立即给404)
  2. 对于所有其他IP:如果请求的内容尚未在caching中立即从文件中加载并将其存储在caching中(所以如果我删除文件,它应该在caching期间服务)

这是我目前的configuration:

server { listen 80; listen 127.0.0.1:9999 default; server_name storage.example.com; charset utf-8; autoindex off; access_log "/var/log/nginx/storage.access.log"; udplog_tag "www.example.com/storage"; set_real_ip_from 127.0.0.0/8; set_real_ip_from unix:; real_ip_header X-Real-IP; server_name_in_redirect off; port_in_redirect off; location /a/ { alias "/storage/public/a/"; } location /b/ { alias "/storage/public/b/"; } } server { listen 80; server_name static.example.com; charset utf-8; autoindex off; access_log "/var/log/nginx/static.access.log"; udplog_tag "www.example.com/static"; location / { proxy_set_header Host "$host"; proxy_pass http://127.0.0.1:9999/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 15; proxy_send_timeout 60; proxy_read_timeout 60; include proxy_cache; proxy_redirect default; } } 

这是包含的文件proxy_cache的内容:

 proxy_cache cache; proxy_cache_key "$scheme://$host$uri"; proxy_cache_use_stale error; proxy_next_upstream off; proxy_cache_min_uses 1; proxy_cache_valid 200 302 1h; proxy_cache_valid 301 1d; proxy_cache_valid any 30m; proxy_buffers 128 4k; 

我想要做的是类似的事情:

 if ( $remote_addr != "ip to exclude" ) { include proxy_cache; } 

不幸的是,这是行不通的。 任何帮助是极大的赞赏。 谢谢。

绕过caching是通过proxy_cache_bypass完成的。 如果您传递给它的任何值不为零,它将导致caching被绕过。

但在这之前,你需要一个variables来传递给它。 在你的情况下,这可以通过geo指令来检查远程IP地址。 (也可以用一张map来完成,这是一个比较一般的指令。)

所以,首先在你的http块中:

 geo $ip_cache_bypass { default 0; 192.0.2.81 1; } 

然后在你的代理configuration指令中:

 proxy_cache_bypass $ip_cache_bypass; 

caching将被绕过IP地址192.0.2.81。 您可以在geo块中添加尽可能多的IP地址或CIDR范围。