Zol*_*tán 13 proxy caching nginx
我想根据请求中的自定义标头有条件地从缓存中获取文件.
如果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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是该try_files指令总是传递到我的@remote位置,即使缓存提取的文件也是如此.如何判断文件何时返回@local?
Ahm*_*rif 31
try_files指令只接受一个命名位置,所以显然它适用于最后一个.此博客文章提出了一种适用于您的案例的解决方法.如果您不读取整个帖子,可以在@local块的末尾添加以下行:
proxy_intercept_errors on;
recursive_error_pages on;
error_page 404 = @remote;
Run Code Online (Sandbox Code Playgroud)
并改变你try_files的想法:
try_files /$uri @local;
Run Code Online (Sandbox Code Playgroud)