2013-08-30 119 views
0

我使用ngnix作爲反向代理服務器。後臺服務器關閉時會出現這種情況,我知道這一點。因此,我添加了'Check-Cache'頭部來請求,我想要做的是在緩存中獲取文件,以及不僅僅是返回錯誤頁面。我不想將請求傳遞給後端。Nginx在緩存中返回文件/檢查緩存中是否存在文件

情景

$ curl -s -o /dev/null -w "%{http_code}" 0/images/2.jpg -H'Host: example.com' 
200 
$ pkill -9 backend_server 
$ curl -s -o /dev/null -w "%{http_code}" 0/images/2.jpg -H'Host: example.com' -H'Check-Cache: true' 
404 <-- I want to 200 here 

nginx.conf

server { 
    listen  80; 

    underscores_in_headers on; 
    proxy_cache_purge on; 

    location/{ 
     error_page 599 = @jail; 
     recursive_error_pages on; 

     if ($http_check_cache = "true") { 
      return 599; 
     } 

     proxy_pass http://localhost:8080; 
     proxy_set_header Host $host; 
     proxy_cache my-cache; 
     proxy_cache_valid 200 302 10m; 
     proxy_cache_valid 404  1m; 
     proxy_cache_key $uri$is_args$args; 
    } 

    location @jail { 
     # try_files ?? 
     # proxy_cache_key (If i can get it i can use try_files) 
     # what other solution... 
     return 404; 
    } 
} 

回答

0

好的,也許不是很漂亮解決方案,但上游可以與makred作爲向下一臺服務器來使用。

http { 
upstream backend-jail { 
    server 0.0.0.0 down; 
} 

server { 
    listen  80; 

    underscores_in_headers on; 

    recursive_error_pages on; 
    error_page 597 = @jail; 

    location/{ 
     if ($http_x_backend_down = "1") { 
      return 597; 
     } 

     proxy_pass http://lcoalhost:8080;    
     proxy_set_header Host $host; 

     proxy_cache my-cache; 
     proxy_cache_valid 200 302 1h; 
     proxy_cache_valid 404  1m; 
     proxy_cache_key $uri$is_args$args; 
    } 

    location @jail { 
     # dont need to log error about 'no live upstreams' 
     error_log /dev/null crit; 

     # backend-jail always return 502, want 404 to be returned. 
     error_page 502 =404 /; 

     proxy_pass http://backend-jail; 
    } 
} 
}