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:
1 2 3 4 |
location ~ ^/get_text { default_type text/html; return 200 'This is test text!'; } |
Fixed json:
1 2 3 4 |
location ~ ^/get_json { default_type application/json; return 200 '{"status":"success","result":"nginx test 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:
1 2 3 4 5 6 |
location ~ ^/get_text/article/(.*)_(\d+).html$ { default_type text/html; set $s $1; set $d $2; return 200 str:$s$d; } |
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
1 |
add_header Content-Type 'text/html; charset=utf-8'; |
Now, the browser knows which encoding we are using.
Or replace the add_header line with
1 |
charset utf-8; |
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/