NGINX Custom Error Response

NGINX Custom Error Response

If you use NGINX as a proxy, you may want to use a custom error response, because the default error response from NGINX is not pretty. Read this post to know how to use custom error responses in NGINX.

The default error response from NGINX is in an HTML format. It looks like this.

NGINX 502 Bad Gateway
The 502 error is received if the upstream service is down. It’s not pretty right? Imagine showing this error page to your customers.

Custom Error Page in HTML

To show your custom error page when NGINX got errors you see this sample config file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
server {
    server_name  localhost;
    listen 80;

    error_page 502 @html502error;

    location / {
        proxy_pass http://192.168.100.17:5005;
    }

    location @html502error {
        root /var/html;
        try_files /error502.html 502;
    }
}

In this example, we will return our custom page for 502 errors. The page that will be returned is an HTML file errors502.html in directory /var/html. We define that error page for code 502 by using error_page 502 @html502error; on line 8. The location of @html502error is defined on lines 11 to 14, where we define the root directory and the file location. The try_files function will return the specified page, that is errors502.html. If the file is not found, it will return the default 502 code.

Custom Error in JSON

If your upstream server respond with JSON, you can use this code for the location of error response.

1
2
3
4
location @json502error {
    default_type application/json;
    return 502 '{"errors": "server is not up"}';
}
It will return JSON response with code 502.

Intercept Upstream Response

Please note that by default NGINX only intercept the error that is generated by NGINX itself. If the upstream deliberately return an error code, for example, 502, NGINX will return the response without intercepting. To make NGINX intercept the errors from the upstream server, you need to set proxy_intercept_errors to on. It can be put in server directive.

Full config example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
server {
    server_name  localhost;
    listen 80;

    proxy_intercept_errors on;

    error_page 502 @json502error;

    location / {
        proxy_pass http://192.168.100.17:5005;
    }

    location @json502error {
        default_type application/json;
        return 502 '{"errors": "server is not up"}';
    }
}


See also

comments powered by Disqus