温馨提示×

nginx返回文本或json的方法是什么

小亿
377
2023-06-28 15:12:32
栏目: 编程语言

要在Nginx返回文本或JSON,您可以使用以下方法之一:
1. 使用`add_header`指令:可以在Nginx配置中使用`add_header`指令来添加自定义的响应头。您可以在`location`块中添加以下指令:
```
location /api {
   add_header Content-Type text/plain;
   return 200 "This is a plain text response";
}
```
这将在`/api`路径下返回纯文本响应。
2. 使用`return`指令:您可以使用`return`指令在Nginx配置中直接返回文本或JSON响应。例如:
```
location /api {
   return 200 '{"message": "This is a JSON response"}';
}
```
这将在`/api`路径下返回JSON响应。
3. 使用Lua模块:如果您启用了Lua模块,您可以使用Lua脚本来生成并返回文本或JSON响应。例如:
```lua
location /api {
   default_type 'text/plain';
   content_by_lua_block {
       ngx.say("This is a plain text response")
   }
}
```
这将在`/api`路径下返回纯文本响应。

0