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

6

我目前需要避免缓存Ajax请求,但仍要缓存结果页面。

我知道哪些指令禁止缓存: proxy_no_cache或proxy_cache_bypass, 但如何添加适当的语句呢?通过if块吗? 语句应该像这样:

$http_x_requested_with=XMLHttpRequest

谢谢;) 更新 这样可以吗?
proxy_cache_bypass  $http_x_requested_with=XMLHttpRequest;
proxy_no_cache      $http_x_requested_with=XMLHttpRequest;
2个回答

6
在location块内使用if语句块可能会很棘手(http://wiki.nginx.org/IfIsEvil)。因此最好将其放在location块外。然而,这样做会影响性能,因为所有请求都必须通过该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;
}

4
这对我有效:

这个方法适用于我:

if ($http_x_requested_with = XMLHttpRequest) {
    set $nocache 1;
}

你把这个配置放在哪里?我的意思是服务器块还是位置。 - Erick Vivanco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接