在 Nginx 中,你可以通过几种不同的方式配置服务器直接返回文本或 JSON 数据,而不需要依赖后端服务。以下是几种常见的方法:
return
指令返回文本server {
listen 80;
server_name example.com;
location /text-response {
add_header Content-Type text/plain;
return 200 "This is a plain text response from Nginx";
}
}
echo
模块返回文本(需要安装 ngx_http_echo_module)location /echo-text {
default_type text/plain;
echo "This is text from echo module";
}
location /json-response {
add_header Content-Type application/json;
return 200 '{"status": "success", "message": "This is a JSON response"}';
}
location /echo-json {
default_type application/json;
echo '{"status": "success", "message": "JSON from echo module"}';
}
location /file-text {
root /path/to/files;
default_type text/plain;
try_files /textfile.txt =404;
}
location /file-json {
root /path/to/files;
default_type application/json;
try_files /data.json =404;
}
location /lua-json {
default_type application/json;
content_by_lua '
ngx.say([[{"status": "success", "data": {"id": 123, "name": "Nginx Lua"}]])
';
}
application/json
echo
模块需要额外安装,默认 Nginx 不包含此模块server {
listen 80;
server_name api.example.com;
# 返回纯文本
location /status {
add_header Content-Type text/plain;
return 200 "Service is running";
}
# 返回静态JSON
location /api/health {
add_header Content-Type application/json;
return 200 '{"status": "healthy", "timestamp": "$time_iso8601"}';
}
# 从文件返回JSON
location /api/config {
root /var/www/json;
default_type application/json;
try_files /config.json =404;
}
# 使用Lua返回动态JSON
location /api/dynamic {
default_type application/json;
content_by_lua '
local time = ngx.localtime()
ngx.say(string.format([[{"server_time": "%s", "request_id": "%s"}]],
time, ngx.var.request_id))
';
}
}
以上配置可以根据你的具体需求进行调整和组合使用。