nginx returns html instead of json response

Maxim Dounin mdounin at
Tue Nov 8 05:48:33 UTC 2022


On Mon, Nov 07, 2022 at 08:59:51PM +0530, Kaushal Shriyan wrote:

> I am running the nginx version: nginx/1.22 as a reverse proxy server on
> CentOS Linux release 7.9.2009 (Core). Is there a way to return json
> response when i hit* instead of the html
> response.
> location /api/v1/* {
>     internal;
>     add_header 'Content-Type' 'application/json charset=UTF-8';
>     error_page 502 '{"error": {"status_code": 502,"status": "Bad
> Gateway"}}';
> }
> But whenever I try to send a request to /api/v1/users via curl I get the
> HTML source code in response instead of JSON response.
> Please guide me. Thanks in advance. I look forward to hearing from you.

First of all, the "/api/v1/*" does not look like a valid prefix.  
Note that "*" is not special in prefix locations, so you need just 
"/api/v1/" to match relevant requests.  See for details.

Further, trying to overwrite the Content-Type returned with the 
add_header directive will fail, as nginx will still send the 
Content-Type as set by the "types" and "default_type" directive.  
See for details.  To set charset you can 
use the "charset" directive, see

Additionally, the "error_page" directive does not accept strings.  
If you want to return a string directly from nginx in case of an error, 
you can use error_page with an internal URI, and then use the 
"return" directive to return the text.  See and for 

And, as already pointed out in another response, the "internal" 
directive implies that the location won't be accessible from the 
outside, so you have to remove it.  See for details.

Further, your location does not contain actual proxying - so you 
probably want to add some, or all matched requests will be 
considered requests to static files.

Summing the above, valid configuration will look like:

location /api/v1/ {
    error_page 502 /error502;
    proxy_pass ...

location = /error502 {
    default_type text/json;
    charset UTF-8;
    charset_types text/json;
    return 200 '{"error": {"status_code": 502,"status": "Bad Gateway"}}';

It might be a good idea to start with reading some introductory 
articles at, notably:

Beginner’s Guide


How nginx processes a request

Hope this helps.

Maxim Dounin

More information about the nginx mailing list