目录

  • nginx 变量使用
  • 常见内置变量
  • 日志模块
  • 自定义json日志格式

nginx 变量使用

nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用,变量可以分为内置变量和自定义变量,内置变量是由nginx模块自带,通过变量可以获取到众多的与客户端访问相关的值

常见内置变量

变量

说明

$remote_addr

存放了客户端的地址,注意是客户端的公网IP

$args

变量中存放了URL中的指令

$document_root

保存了针对当前资源的请求的系统根目录,如/apps/nginx/html

$document_uri

保存了当前请求中不包含指令的URI,注意是不包含请求的指令,如http://www.a.net/main/index.do?id=090&partner=search,会被定义为/main/index.do

$host

存放了请求的host名称

$http_user_agent

客户端浏览器的详细信息

$http_cookie

客户端的cookie信息

$remote_port

客户端请求Nginx服务器时客户端随机打开的端口$remote_user

$request_body_file

做反向代理时发给后端服务器的本地资源的名称

$request_method

请求资源的方式,GET/PUT/DELETE等

$request_filename

当前请求的资源文件的路径名称,由root或alias指令与URI请求生成的文件绝对路径,如/apps/nginx/html/main/index.html

$request_uri

包含请求参数的原始URI,不包含主机名,如:main/index.do?id=090&partner=search 。

$scheme

请求的协议,如ftp,https,http等。

$server_protocol

保存了客户端请求资源使用的协议版本,如HTTP/.0,HTTP/.,HTTP/.0等

$server_addr

保存了服务器的IP地址

$server_name

请求的服务器的主机名。

$server_port

请求的服务器的端口

自定义变量:假如需要自定义变量名称和值,使用指令set $variable value 方法如下:

set $variable value;

#支持:server, location, if

示例:

# echo 需要echo模块
set $name magedu;
echo $name;

set $my_port $server_port;
echo $my_port;
echo "$server_name:$server_port";

日志模块

ngx_http_log_module模块

  1. log_format
    指定日志格式记录请求
Syntax:	    log_format name [escape=default|json|none] string ...;
Default:    log_format combined "...";
Context:    http

string可以使用nginx核心模块及其它模块内嵌的变量

  1. access_log
    访问日志文件路径,格式及相关的缓冲的配置
Syntax:	    access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
            access_log off;
Default:    access_log logs/access.log combined;
Context:    http, server, location, if in location, limit_except

示例

log_format 格式名 '$remote_addr-$remote_user [$time_local] '
        '"$request" $status $bytes_sent '
        '"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log /spool/logs/nginx-access.log 格式名 buffer=32k;

自定义json日志格式

nginx 的默认访问日志记录内容相对比较单一,默认的格式也不方便后期做日志统计分析,生产环境中通常将nginx日志转换为json日志,然后配合使用ELK做日志收集-统计-分析

json格式的访问日志格式:

{
    "@timestamp":"2019-02-22T08:55:32+08:00",
    "host":"192.168.7.102",
    "clientip":"192.168.0.1",
    "size":162,
    "responsetime":0.000,
    "upstreamtime":"-",
    "upstreamhost":"-",
    "http_host":"www.magedu.net",
    "uri":"/favicon.ico",
    "domain":"www.magedu.net",
    "xff":"-",
    "referer":"-",
    "tcp_xff":"",
    "http_user_agent":"Mozilla/5.0 (Windows NT 6.1;Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0",
    "status":"404"
}

自定义json日志示例:

log_format access_json '{
    "@timestamp":"$time_iso8601",'
    '"host":"$server_addr",'
    '"clientip":"$remote_addr",'
    '"size":$body_bytes_sent,'
    '"responsetime":$request_time,'
    '"upstreamtime":"$upstream_response_time",'
    '"upstreamhost":"$upstream_addr",'
    '"http_host":"$host",'
    '"uri":"$uri",'
    '"domain":"$host",'
    '"xff":"$http_x_forwarded_for",'
    '"referer":"$http_referer",'
    '"tcp_xff":"$proxy_protocol_addr",'
    '"http_user_agent":"$http_user_agent",'
    '"status":"$status"}';

access_log /apps/nginx/logs/access_json.log access_json;

json格式的日志访问统计, python代码示例

#cat nginx_json.py
#!/usr/bin/env python
#coding:utf-8
status_200= []
status_404= []
with open("access_json.log") as f:
    for line in f.readlines():
        line = eval(line)
        if line.get("status") == "200":
        status_200.append(line.get)
        elif line.get("status") == "404":
        status_404.append(line.get)
    else:
        print("状态码 ERROR")
        f.close()
print "状态码200的有--:",len(status_200)
print "状态码404的有--:",len(status_404)
  1. open_log_file_cache
    缓存各日志文件相关的元数据信息
Syntax:	    open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
            open_log_file_cache off;
Default:    open_log_file_cache off;
Context:    http, server, location

max:缓存的最大文件描述符数量
min_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项
inactive:非活动时长
valid:验证缓存中各缓存项是否为活动项的时间间隔

favicon.ico

favicon.ico 文件是浏览器收藏网址时显示的图标,当使用浏览器访问页面时,浏览器会自己主动发起请求获取页面的favicon.ico文件,但是当浏览器请求的favicon.ico文件不存在时,服务器会记录404日志,而且浏览器也会显示404报错

解决方案:
服务器不记录访问日志:

location = /favicon.ico {
    log_not_found off;
    access_log off;
}

将图标保存到指定目录访问:

#location ~ ^/favicon\.ico$ {
location = /favicon.ico {
    root /data/nginx/html/pc/images;
}