2

Usually I have in nginx config rules which does not allow cache all XMLHttpRequest:

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

Is there a way to cache only GET Ajax request?

AD7six
  • 2,810
  • 2
  • 20
  • 23

2 Answers2

1

Use the $request_method

It's unshown, but assumed there's an if block in the config like so:

if ($nocache_01) {
    ...
}

Instead, by concatenating this variable with the request method, a more explicit check is possible i.e.:

if ($nocache_01$request_method = "1GET") {
    ...
}

Or, e.g., without using a map at all:

if ($http_x_requested_with$request_method = "XMLHttpRequestGET") {
    ...
}
AD7six
  • 2,810
  • 2
  • 20
  • 23
  • Thank for [AD7six](http://serverfault.com/users/108287/ad7six) for prompting. Now, my maps looks as it. `map $http_x_requested_with $nocache_01 { default 0; XMLHttpRequestGET 0; XMLHttpRequestPUT 1; XMLHttpRequestPATCH 1; XMLHttpRequestDELETE 1; XMLHttpRequestPOST 1; } ` – Rostyslav Malenko Dec 03 '14 at 10:28
  • 1
    Your comment is missing `$request_method` - But I wondered if you'd choose do that =). Note that a map [can be a regex](http://nginx.org/en/docs/http/ngx_http_map_module.html) so e.g. `~XMLHttpRequest 1;` takes care of all the other XHR permutations. – AD7six Dec 03 '14 at 14:53
  • AD7six, thank you again :) Do you mean something like this? `map $http_x_requested_with$request_method $nocache_01 { default 0; XMLHttpRequestGET 0; ~XMLHttpRequest(PUT|PATH|DELETE|POST) 1; } ` I use this variable here `fastcgi_no_cache $nocache_01; fastcgi_cache_bypass $nocache_01;` – Rostyslav Malenko Dec 03 '14 at 18:42
  • 1
    @RostyslavMalenko yes. Though you don't need `(PUT|PATH|DELETE|POST)` if by that you really mean "all other http methods". It's appropriate btw to write an answer to your own question - if it differs from other existing answers. – AD7six Dec 03 '14 at 19:01
1

Thank for AD7six for prompting. Now, my maps looks as it.

map $http_x_requested_with$request_method $nocache_01 { default 0; XMLHttpRequestGET 0; ~XMLHttpRequest(PUT|PATH|DELETE|POST) 1; }

This is mean that XMLHttpRequest(PUT|PATH|DELETE|POST) will not be cached

fastcgi_no_cache $nocache_01; fastcgi_cache_bypass $nocache_01;