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.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.
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.
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
on. It can be put in server directive.
Full config example: