首页 > 系统相关 >nginx返回指定数据

nginx返回指定数据

时间:2024-08-08 09:27:14浏览次数:8  
标签:返回 200 return get text 指定 nginx html http

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

标签:返回,200,return,get,text,指定,nginx,html,http
From: https://www.cnblogs.com/kkit/p/18348311

相关文章