Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: How to prevent caching ajax requests on proxy?

Tags:

nginx

I currently need to avoid caching Ajax requests, but to keep caching the result pages.

I know which directives disallow caching: proxy_no_cache or proxy_cache_bypass But how to add a proper statement. Via if block? The statement should be like this?

$http_x_requested_with=XMLHttpRequest

Thanks ;)

Update

Like that?

proxy_cache_bypass  $http_x_requested_with=XMLHttpRequest;
proxy_no_cache      $http_x_requested_with=XMLHttpRequest;
like image 292
Somebody Avatar asked May 21 '11 19:05

Somebody


2 Answers

Using if block inside a location block could be tricky (http://wiki.nginx.org/IfIsEvil). So it's better to be put outside the location block. However, doing that affects performance because all requests have to go through that if block.

It's better to use map directive (http://wiki.nginx.org/HttpMapModule) to set the variable and then use that variable in the proxy directives. Performance is better (see how it works in the above link).

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

server {
    ...
    proxy_cache_bypass  $nocache;
    proxy_no_cache      $nocache;
}
like image 108
Chuan Ma Avatar answered Nov 15 '22 06:11

Chuan Ma


this works for me:

if ($http_x_requested_with = XMLHttpRequest) {
    set $nocache 1;
}
like image 44
Bhansson Avatar answered Nov 15 '22 06:11

Bhansson