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?

2 Answers 2

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") {
    ...
}
4
  • Thank for 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; } Dec 3, 2014 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 so e.g. ~XMLHttpRequest 1; takes care of all the other XHR permutations.
    – AD7six
    Dec 3, 2014 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; Dec 3, 2014 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 3, 2014 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;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .