How to configure nginx to return text or json

V Records 29,690 Views No comment

Sometimes when you request some interfaces, you need to return the specified text string or json string. If it is a simple logic or a fixed string, you can use nginx to implement it quickly, so you don’t need to write a program to respond to the request. using nginx can reduce server resource usage and make response performance very fast.

First look at how to return fixed text and json, they are configured in the nginx server segment to configure the location item to intercept, the configuration example is as follows:

Fixed text:

Fixed json:

Reloading the configuration after saving will take effect. Note here: default_type must be added, otherwise the browser will download it as an unrecognized file.

In addition, you can simply return different strings based on the requested URL. Here is an example:

This can simply intercept the string in the url, of course, you can use (.*) to match all, in fact, according to different needs can be defined

The above are some simple cases. In the server environment, for some simple processing, you can use nginx to save some programming work.

Also add the Chinese display problem, because Linux uses the character encoding of UTF-8. By default, our browser will render the page with GBK code if the server does not specify the encoding or the static page does not declare the encoding. So, by default, when the browser returns Chinese, the browser uses gbk to parse the utf-8 encoding. Obviously, garbled characters will appear. At this time, the header is actively added in the location block of nginx to output the correct encoding.

We need to add

Now, the browser knows which encoding we are using.
Or replace the add_header line with

it is also possible


This article was first published by V on 2018-11-09 and can be reprinted with permission, but please be sure to indicate the original link address of the article :http://www.nginxer.com/records/how-to-configure-nginx-to-return-text-or-json/

Leave a Reply

Your email address will not be published. Required fields are marked *

Go