How to configure nginx to return text or json

PHPz
Release: 2023-05-18 13:19:14
forward
2278 people have browsed it

先看返回固定的文本和json,都是在server中配置location拦截即可,配置示例如下:

固定文本:

location ~ ^/get_text {
  default_type text/html;
  return 200 'this is text!'; 
}
Copy after login

固定json:

location ~ ^/get_json {
  default_type application/json;
  return 200 '{"status":"success","result":"nginx json"}';
}
Copy after login

保存后重新载入配置即可生效,注意:default_type必须要添加,否则浏览器会当成不识别的文件进行下载

另外也可以简单的根据请求的url返回不同的字符串,示例如下:

location ~ ^/get_text/article/(.*)_(\d+).html$ {
  default_type text/html;
  set $s $1;
  set $d $2;
  return 200 str:$s$d;
}
Copy after login

这样可以简单截取url中的字符串,当然也可以用(.*)匹配所有的,实际中根据不同需求定义即可

上面的就是一些简单的案例,在服务器环境中对于简单的处理,充分使用nginx可以省去一些编程工作

另外补充一下中文显示的问题,因为linux下采用的是utf-8的字符编码,默认情况下我们的浏览器在服务器没有指定编码或者静态页面没有声明编码的情况下会以gbk的编码去渲染页面,这样默认情况下返回中文的话浏览器用gbk来解析utf-8编码,显然会出现乱码,这时要在nginx location块中主动添加header来输出正确编码,添加内容为: add_header content-type 'text/html; charset=utf-8'; 这样浏览器就知道我们使用的是哪种编码了,如下图:

How to configure nginx to return text or json

或者把add_header这行换成 charset utf-8; 也是可以的

The above is the detailed content of How to configure nginx to return text or json. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!