Nginx:如何防止在代理上缓存ajax请求?

Som*_*ody 6 nginx

我目前需要避免缓存Ajax请求,但要保持缓存结果页面.

我知道哪些指令不允许缓存:proxy_no_cache或proxy_cache_bypass但是如何添加正确的语句.通过if块?声明应该是这样的?

$http_x_requested_with=XMLHttpRequest
Run Code Online (Sandbox Code Playgroud)

谢谢 ;)

更新

像那样?

proxy_cache_bypass  $http_x_requested_with=XMLHttpRequest;
proxy_no_cache      $http_x_requested_with=XMLHttpRequest;
Run Code Online (Sandbox Code Playgroud)

Chu*_* Ma 5

在位置块中使用if块可能很棘手(http://wiki.nginx.org/IfIsEvil).因此最好放在位置块之外.但是,这样做会影响性能,因为所有请求都必须通过if块.

最好使用map指令(http://wiki.nginx.org/HttpMapModule)来设置变量,然后在代理指令中使用该变量.性能更好(请参阅上述链接中的工作原理).

map $http_x_requested_with $nocache {
    default 0;
    XMLHttpRequest 1;
}

server {
    ...
    proxy_cache_bypass  $nocache;
    proxy_no_cache      $nocache;
}
Run Code Online (Sandbox Code Playgroud)


小智 4

这对我有用:

if ($http_x_requested_with = XMLHttpRequest) {
    set $nocache 1;
}
Run Code Online (Sandbox Code Playgroud)