Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Return common errors as json in Nginx
error_page 500 /500.html;
location /500.html{
return 500 '{"error": {"status_code": 500,"status": "Internal Server Error"}}';
}
error_page 502 /502.html;
location /502.html{
return 502 '{"error": {"status_code": 502,"status": "Bad Gateway"}}';
}
error_page 503 /503.html;
location /503.html{
return 503 '{"error": {"status_code": 503,"status": "Service Temporarily Unavailable"}}';
}
error_page 504 /504.html;
location /504.html{
return 504 '{"error": {"status_code": 504,"status": "Gateway Timeout"}}';
}
error_page 400 /400.html;
location /400.html{
return 400 '{"error": {"status_code": 400,"status": "Bad Request"}}';
}
error_page 401 /401.html;
location /401.html{
return 401 '{"error": {"status_code": 401,"status": "Unauthorized"}}';
}
error_page 403 /403.html;
location /403.html{
return 403 '{"error": {"status_code": 403,"status": "Forbidden"}}';
}
error_page 404 /404.html;
location /404.html{
return 404 '{"error": {"status_code": 404,"status": "Not Found"}}';
}
error_page 408 /408.html;
location /408.html{
return 408 '{"error": {"status_code": 408,"status": "Request Timeout}}';
}
error_page 418 /418.html;
location /418.html{
return 418 '{"error": {"status_code": 418,"status": "I\'m a teapot"}}';
}
@eriadam

This comment has been minimized.

Copy link

eriadam commented Jan 18, 2019

You can also add the proper Content-Type to the header:

  error_page 500 /500.html;
  location /500.html {
    more_set_headers 'Content-Type: application/json charset=UTF-8';
    return 500 '{"error": {"status_code": 500,"status": "Internal Server Error"}}';
  }
@adonese

This comment has been minimized.

Copy link

adonese commented Apr 27, 2019

@eriadam more_set_headers is not working. Use add_header instead.
the syntax will be different though.

add_header 'Content-Type' 'application/json charset=UTF-8';

More here

@vinayan3

This comment has been minimized.

Copy link

vinayan3 commented May 14, 2019

If you set the file name endings json then the correct Content-Type header is generated. You can see that in the latest Nginx mime type file, https://github.com/nginx/nginx/blob/master/conf/mime.types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.