Nginx 自定义输出

这种方式实际上是特别有用且被人忽略的配置, 能够有效节约某些负载情况.

比如以下情况:

  • 如果服务器宕机返回 404 错误但是要求返回 JSON 根据 POST 请求返回 JSON.
  • 需要设置在某个页面只需要设置固定文本展示在页面
  • 设置域名之下的展示 PUBLIC_KEY 来展示公钥数据提供准备解密文本

这种方法适合常规的固定字符串数据展示, 但是需要注意必须要在 http-server-location 块之中.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 必须在 http 块中配置
http {
......
# 声明默认的 UTF-8 编码
charset utf-8;

# 一般其他配置文件都是防止于 `/etc/nginx/conf.d/xxx.conf`
# 这里当作其他配置选项设置
server{
listen 80;

# 这里可以直接配置访问的配置
# 访问地址为: http://127.0.0.1/
location / {
# 设置默认的返回格式
default_type text/html;

# 这里返回 http 为了兼容中文最好添加头信息
add_header Content-Type 'text/html; charset=utf-8';

# 设置返回的内容和状态码( 200 )
return 200 'hello.world!中文';
}

# 设置 JSON 返回数据格式
# 访问地址: http://127.0.0.1/json
location /json {
default_type application/json;

# 展示返回的 JSON 数据
return 200 '{"status":200, "message":"request success"}';
}

# 设置自定义的返回格式数据
# 访问地址: http://127.0.0.1/404
location /404 {
default_type application/json;

# 格式化需要的数据
set $response_code 404;
set $response_message "Not Found";
set $response_address $remote_addr;

# 格式化返回数据
return 404 "{\"status\":${response_code},\"message\":\"${response_message}\",\"ip_address\":\"${response_address}\"}";
}
}
}

除此之外可以依托 Nginx 的内部变量来处理成一些简单的公网服务:

1
2
# 创建基建服务业务配置
sudo vim /etc/nginx/conf.d/status.conf

/etc/nginx/conf.d/status.conf 主要就是用来请求暴露 HTTP 一些信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
server{
listen 80;
charset utf-8; # server 块也能声明默认字符集

# 可以设置为 / 或者 /status 挂靠, 主要查看一些服务器状态
location / {
default_type application/json;

# 这里就需要讲解 nginx 一些系统变量, 这里摘选几个请求参数变量即可, 其他变量最好不要暴露给客户端:
# $remote_addr: 远程也就是客户端的IP地址
# $connection: 当前的链接的唯一标识
# $connection_requests: 当前连接上已处理的请求数(长连接下会累加), 可以确认目前挤占服务有多少连接数
# $scheme: 请求使用的协议(http/https)
# $server_protocol: 请求使用的协议版本(如 HTTP/1.1、HTTP/2、...)
# $status: 响应的 HTTP 状态码(如 200、404、500、...)
# $request_time: 请求处理总耗时(秒,含小数,如 0.058 秒), 可以确认监控服务器是否出现请求阻塞情况
# 其他的系统变量不推荐暴露给客户端
#
# 那么现在就可以自定义一个状态 JSON 返回给客户端
return 200 '{"scheme":"$scheme",
"protocol":"$server_protocol",
"client_ip":"$remote_addr",
"connection_id":"$connection",
"connection_requests":$connection_requests,
"request_time":$request_time,
"status_code":$status
}';
}
}