wonderbeyond
4/28/2015 - 2:35 PM

nginx proxy_cache configuration sample, with url-based-update support

nginx proxy_cache configuration sample, with url-based-update support

http {
    # ... ...

    proxy_cache_path /var/cache/nginx/ levels=1:2 keys_zone=api_cache:100m;

    server {
        listen       80;
        server_name  localhost;

        add_header X-Upstream-Cache-Status $upstream_cache_status;
        proxy_cache_valid 200 304 10m;

        # proxy_cache_bypass 会绕过而不读缓存, 但不影响正常更新缓存.
        # 配在server下面, 是为了被不同的location共享
        proxy_cache_bypass $update_required;

        ## **疑问**:
        # 我看别人的例子里面proxy_cache_bypass都是写在location里面,我为了避免冗余放到了server里面,经过测试是靠谱的!
        # 但是,其中的 $update_required 变量是在server下面引用的,它究竟是如何应用到location并在恰当的时机根据不同的请求引用了正确的值?
        # 各种配置指令在什么时候开始消化变量?作为初学者,看官网文档能够我提供的帮助有限,希望能获得一些提示。

        location ~ ^/update(/.*)$ {
            # 触发缓存主动更新($update_required=1 相当于主动更新缓存), 在 url 前加 /update 访问
            # 设置 $update_required 变量后转交(rewrite...last)给对应的location,
            set $path $1;
            set $update_required 1;
            rewrite ^ $path last;
        }

        location /api/ {
            proxy_pass http://127.0.0.1:8000;
            proxy_cache api_cache;
            proxy_cache_key $scheme$proxy_host$uri$is_args$args;
        }
    }
}