I want to fetch a file from the cache conditionally, based on a custom header in the request.
If the X-Proxy
header is present in the request, return the file only if it's present in the cache. Otherwise fetch it from the internet if necessary.
Here's my .conf
file:
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;
}
}
}
The problem is that the try_files
directive always passes into my @remote
location, even if the fetched file is cached. How do I tell it that the file was found when it returns from @local
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…