JerseyGood
JerseyGood

Reputation: 191

NGINX conditionally turn on/off proxy_intercept_errors

I got 2 clients that may send same HTTP request to Server through nginx proxy.

one is browser the other is my own program, the difference is request send from my own program have custom HEADER my-header=me

My goal is: if any request leads to a http:500 response of the Server, I would like the browser to show an Error page and my own program log the original response from server which contains Exception stacks.

With nginx proxy_intercept_errors=on and error_page 500 /500.html I can navigate to error page for browser requests, but I will also log this html page in my own program which I don't want.

I have search a while for solutions such as conditional proxy_intercept_errors or return/rewrite original response before proxy but got no answers.

How I achieve my goal by nginx settings?

Upvotes: 3

Views: 3914

Answers (1)

TinyRoy
TinyRoy

Reputation: 309

You should be able to use Nginx map to detect the header value to create a switch.

Then you should be able to use rewrite to route accordingly to the desired location block

map $http_my_header $intercept {
  default "intercept_on";
  me "intercept_off";
}
server {
  listen 80 default_server;

  location /test {
    rewrite /test /$intercept last;
  }

  location /intercept_on {
    proxy_intercept_errors on;
    default_type text/plain;
    echo "Intercept errors is: On";
  }

  location /intercept_off {
    proxy_intercept_errors off;
    default_type text/plain;
    echo "Intercept errors is: Off";
  }
}

Beside rewrite, you could also use try_files with @ named location but don't think it was meant for this.

Upvotes: 1

Related Questions