【问题标题】:NGINX try_files with multiple named locations具有多个命名位置的 NGINX try_files
【发布时间】:2014-02-12 17:49:03
【问题描述】:

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

如果请求中存在X-Proxy 标头,则仅当文件存在于缓存中时才返回该文件。否则,如有必要,请从 Internet 获取。

这是我的.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返回时,如何告诉它文件已找到?

【问题讨论】:

    标签: caching nginx proxy


    【解决方案1】:

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

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

    并将您的 try_files 更改为:

    try_files /$uri @local;
    

    【讨论】:

    • "try_files 指令只接受一个命名位置" - 该信息是黄金,我不知道,我在文档中找不到它。然而,这个技巧的重要部分是在error_page 指令中。非常感谢,现在一切正常!
    • 是的,文档根本没有这么说,甚至没有抱怨——它只是没有按照您的要求做。跛脚。
    • 我在这上面花了几个小时。自 2018 年 10 月起,命名后备位置仍需要此解决方法。
    • 抱歉,找不到the blog post。有人知道替代链接吗?
    猜你喜欢
    • 1970-01-01
    • 2016-10-24
    • 2013-07-31
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    相关资源
    最近更新 更多