How can I configure nginx to return an error_page if the URI does not contain ajax
but if it does contain ajax
don't send an error page and just return the response? Something like the following but I can't figure out how to access $status. I want to do this for all statuses that are 4xx or 5xx
Essentially, I want to be able to receive a JSON response when there is an AJAX request error and an error page when the request failed to render HTML
# If the location contains ajax
location ~ ajax {
# Return the error status code
return $status;
}
# Location did not contain ajax so send an error page
error_page $status error.html;
Thank you!
CodePudding user response:
It turns out I was thinking about nginx directives wrong. I was thinking about it like a programming language as if the error_page for the non-ajax responses would be evaluated before the URIs containing ajax. Instead, the error_page directive defined in the location block for URIs that match the regex is what will be used. This ended up working perfect.
# All pages error page
error_page 404 400 401 402 403 405 406 407 408 409 410 411 412 413 414 415 416 417 500 501 502 503 504 505 error.html;
location ~ ajax {
# Error page for URI containing ajax
error_page 500 501 502 503 504 505 error.html;
}