nginx返回指定数据

nginx返回指定数据

返回json

### 配置指定路径返回相应json信息
location ~ ^/get_info {
    default_type application/json;
    return 200 '{"status":"success","result":"hello world!"}';
}

注意:当开发某个接口固定是一个返回值时,可以用此方法返回。节省后端处理过程


# 测试
 curl http://www.peter-zhou.com/get_info
{"status":"success","result":"hello world!"}

返回text

### 配置指定路径返回相应text信息
location ~ ^/get_info1 {
    default_type text/html;
    return 200 'hello world!';
}

location ~ ^/get_info2 {
    default_type text/html;
    return 200 '你好,世界!';
}

location ~ ^/get_info3 {
    default_type text/html;
    add_header Content-Type 'text/html; charset=utf-8'; 
    return 200 '你好,世界!';
}

注意:当有些浏览器默认用gbk 来解析就会出现中文乱码,这时候需要添加header转换为utf-8


### 测试
# curl http://www.peter-zhou.com/get_info1
hello world!


#curl http://www.peter-zhou.com/get_info2
你好,世界!


#curl http://www.peter-zhou.com/get_info3 -I
HTTP/1.1 200 OK
Server: Nginx
Date: Fri, 15 Mar 2019 06:21:58 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 16
Connection: keep-alive

根据url返回数据

### 配置匹配规则
location ~ ^/return/(.*)_(\d+).html$ {
    default_type text/html;
    set $string $1;
    set $data   $2;
    return 200 $string:$data;
}

location ~ ^/return/(.*)/(\d+)$ {
    default_type text/html;
    set $string $1;
    set $data $2;
    return 200 $string:$data;
}

注意:根据url参数http://xxx/test.html?name=xxx&id=xxx 同理也可以用这种方式匹配返回




### 测试
#curl http://www.peter-zhou.com/return/test_01.html
test:01

#curl http://www.peter-zhou.com/return/aaa/123
aaa:123
posted @   itk  阅读(239)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示