xuefeng Yang
xuefeng Yang

Reputation: 21

Nginx returns "502 Bad GateWay" + requestUrl when HTTP request returns 502 status code

I want to implement a function.

Nginx returns "502 Bad GateWay" + requestUrl when HTTP request returns 502 status code

How to configure nginx to achieve this function, thank you.

#/usr/local/nginx/lua/auth/404.lua
ngx.say("502 Bad GateWay ")
local request_method = ngx.var.request_method
ngx.say(request_method)
local request_uri = ngx.var.request_uri
ngx.say(request_uri)
#nginx.conf
 proxy_intercept_errors on ;
 error_page 502 /502.html;
 location =/502.html {
      content_by_lua_file "/usr/local/nginx/lua/auth/404.lua";
 }

Upvotes: 0

Views: 3556

Answers (1)

Light.G
Light.G

Reputation: 7274

You need the proxy_intercept_errors directive.
The default value of this directive is off. You must turn it on if you want to intercept response from proxied server with status code bigger/equal than 300(of course, 502 included). More details about this directive.

Here is an example configuration file which I've tested.

upstream tomcat502 {
  server 10.10.100.131:28889; # There is no such a backend server, so it would return 502
}

server {
  listen       10019; # it's up to you
  server_name  10.10.100.133;

  location /intercept502 {
    proxy_intercept_errors on;  # the most important directive, make it on;
    proxy_pass  http://tomcat502/;
    error_page  502 = @502; # redefine 502 error page
  }

  location @502 {
    return 502 $request_uri\n;  # you could return anything you want.
  }
}

After reloading nginx, use curl to test it.

[root@test133 lunatic]# curl http://10.10.100.133:10019/intercept502
/intercept502 
[root@test133 lunatic]# curl http://10.10.100.133:10019/intercept502 -I
HTTP/1.1 502 Bad Gateway
Server: nginx/1.12.1
Date: Wed, 09 Jan 2019 13:48:05 GMT
Content-Type: application/octet-stream
Content-Length: 14
Connection: keep-alive

I have added some explanation up in configuration. Hope it would help.

Upvotes: 1

Related Questions