具有多个命名位置的NGINX try_files

时间:2014-01-22 15:19:23

标签: caching nginx proxy

我想根据请求中的自定义标头有条件地从缓存中获取文件。

如果请求中存在X-Proxy标头,则只有在缓存中存在该文件时才返回该文件。否则,如有必要,请从互联网上获取。

这是我的.conf文件:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    proxy_cache_path /home/nginx/proxy levels=1:2 keys_zone=one:15m inactive=7d max_size=1000m;
    proxy_temp_path  /home/nginx/temp;
    proxy_buffering                 on;
    proxy_set_header   X-Real-IP            $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   Host                   $http_host;
    proxy_set_header   X-NginX-Proxy    true;
    proxy_set_header   Connection "";
    proxy_http_version 1.1;

    server {
        listen       8000;

        location / {
            root /home/nginx/preload;
            try_files /$uri @local @remote;
        }

        location @local {
            internal;
            add_header X-Local true;
            add_header X-Cache $upstream_cache_status;

            proxy_pass http://$http_host$uri$is_args$args;
            proxy_cache             one;
            proxy_cache_key         backend$request_uri;
            proxy_cache_valid       200  1h;
            proxy_cache_use_stale   error timeout invalid_header;
        }

        location @remote {
            resolver 8.8.8.8;
            add_header X-Remote true;
            add_header X-Cache $upstream_cache_status;

            if ($http_x_proxy) {
                return 404;
            }

            proxy_pass http://$http_host$uri$is_args$args;
            proxy_cache             one;
            proxy_cache_key         backend$request_uri;
            proxy_cache_valid       200  1h;
            proxy_cache_use_stale   error timeout invalid_header;

        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

问题是try_files指令总是传递到我的@remote位置,即使缓存了提取的文件也是如此。如何从@local返回文件时告诉它该文件?

1 个答案:

答案 0 :(得分:30)

try_files指令只接受一个命名位置,所以显然它适用于最后一个。这个blog post提出了适用于您的情况的解决方法。如果您不读取整个帖子,可以在@local块的末尾添加以下行:

proxy_intercept_errors on;
recursive_error_pages on;
error_page 404 = @remote;

并将try_files更改为:

try_files /$uri @local;
相关问题