0

Suppose the requirements are like this: The port that Nginx listens on is 80, and the backend server domain name is assumed to be: http://hello.com, Nginx accepts the request from the client as a proxy, and Nginx forwards the request to http://hello.com. If Nginx and the backend server establish a connection timeout, the data in json format must be returned to the client. The data is assumed to be like this:

{ "code": -1 "message":"failed to connect remote error" }

And I want the client to receive a status code of 500. I would like to ask the seniors to achieve this function, how to configure Nginx?

1 Answers1

1

Try the following:

server {
    listen 80;

    server_name auth.example.com;

    set $upstream 111.222.333.444:8080;

    location / {
        proxy_pass_header Authorization;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_intercept_errors on;
        proxy_buffering off;
        client_max_body_size 10M;
        proxy_read_timeout 36000s;
        proxy_redirect off;
        proxy_pass http://$upstream;

        error_page 500 502 503 504 = @outage;
    }

    location @outage {
        return 500 '{ "code": -1 "message":"failed to connect remote error" }';
    }
}

Basically we give it a proxy to the upstream server, then if the upstream server responds with the server-related errors, we'll return our JSON content and a 500 status.

Neekoy
  • 2,325
  • 5
  • 29
  • 48