「Nginx」- 配置调试(打印查看、配置验证、Debug)

  CREATED BY JENKINSBOT

问题描述

Nginx 文档的部分内容没有详细的说明,我们只能通过调试的方式来查看相关变量的值。

该笔记将记录:在 Linux 中,常用的配置文件调试方法,以及常见问题的处理方法。

解决方案

方法一、通过 add_header/return 调试

添加如下配置:

server {
    ...
    location / {
        add_header debug-geoip_city "$geoip_city_continent_code, $geoip_city_country_name, $geoip_city" always;
        # return 200 "$geoip_city_continent_code, $geoip_city_country_name, $geoip_city"
    }
    ...
}

然后使用 CURL 请求,以查看响应头:

# curl --head https://k4nz.com/
HTTP/1.1 404 Not Found
Server: nginx/1.14.0 (Ubuntu)
Date: Mon, 07 Jun 2021 03:44:25 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
debug-geoip_city: AS, China, Yuzhong Chengguanzhen

方法二、通过日志文件

在日志文件中写入某些变量的值,以供我们查看,参考 Log Format 笔记。

方法三、通过 Debug 功能

如果 Nginx 在编译时,启用 –with-debug 选项:

nginx -V 2>&1 | grep -- '--with-debug'

那么能够指定 error_log 配置:

error_log /var/log/nginx/error.log debug;

然后,我们便能够在 error.log 中查看变量值:

...
2021/03/06 15:14:48 [debug] 2550#2550: *1 fastcgi param: "SCRIPT_FILENAME: /usr/lib/cgit/cgit.cgi/something.git/cgit.cgi"
2021/03/06 15:14:48 [debug] 2550#2550: *1 http script copy: "QUERY_STRING"
2021/03/06 15:14:48 [debug] 2550#2550: *1 fastcgi param: "QUERY_STRING: "
2021/03/06 15:14:48 [debug] 2550#2550: *1 http script copy: "REQUEST_METHOD"
2021/03/06 15:14:48 [debug] 2550#2550: *1 http script var: "GET"
2021/03/06 15:14:48 [debug] 2550#2550: *1 fastcgi param: "REQUEST_METHOD: GET"
2021/03/06 15:14:48 [debug] 2550#2550: *1 http script copy: "CONTENT_TYPE"
2021/03/06 15:14:48 [debug] 2550#2550: *1 fastcgi param: "CONTENT_TYPE: "
2021/03/06 15:14:48 [debug] 2550#2550: *1 http script copy: "CONTENT_LENGTH"
2021/03/06 15:14:48 [debug] 2550#2550: *1 fastcgi param: "CONTENT_LENGTH: "
2021/03/06 15:14:48 [debug] 2550#2550: *1 http script copy: "SCRIPT_NAME"
2021/03/06 15:14:48 [debug] 2550#2550: *1 http script var: "/cgit/cgit.cgi/something.git/cgit.cgi"
2021/03/06 15:14:48 [debug] 2550#2550: *1 fastcgi param: "SCRIPT_NAME: /cgit/cgit.cgi/something.git/cgit.cgi"
...

我们未使用该方法,这里仅作记录。

参考文献

How to output variable in nginx log for debugging – Server Fault
NGINX Docs | Debugging NGINX