从零开始的Nginx [ 6 ] --- Nginx的日志配置,log_format 、error_log指令,日志轮转,错误页面配置


nginx 错误页面配置

一、Rewrite 相关指令

1. last,break详解

[root@localhost html]# cat /etc/nginx/conf.d/nginx.conf
server {
    
     
    listen       80;
    server_name  localhost;
    access_log  /var/log/nginx/http_access.log  main;
    error_log /var/log/nginx/last-break.log debug;

    location / {
    
    
        root   /usr/share/nginx/html;
        index  index.html index.htm;
     }
    location /break/ {
    
    
        root   /usr/share/nginx/html;
        rewrite .* /test/break.html break;
     }
    location /last/ {
    
    
        root   /usr/share/nginx/html;
        rewrite .* /test/last.html last;
     }
    location /test/ {
    
    
        root   /usr/share/nginx/html;
        rewrite .* /test/test.html break;
     }

}

[root@localhost conf.d]# cd /usr/share/nginx/html/
[root@localhost html]# mkdir test
[root@localhost html]# echo "last" > test/last.html
[root@localhost html]# echo "break" > test/break.html
[root@localhost html]# echo "test" > test/test.html

测试

[root@localhost html]# curl 127.0.0.1/break/break.html
break
[root@localhost html]# curl 127.0.0.1/test/test.html
test
[root@localhost html]# curl 127.0.0.1/last/last.html
test

当 使用 /last/last.html 访问的时候,会匹配到 /last/
匹配到后,请求的 url 会被重写为 /test/last.html
并且这里的 rewrite .* /test/last.html last;
后面的 flag 是 last ,因此就会使用重写过的 URL /test/last.html
重新进入 server{} 中进行匹配

注意:

  • last 标记在本条 rewrite 规则执行完后,会对其所在的 server { … } 标签重新发起请求;
  • break 标记则在本条规则匹配完成后,停止匹配,不再做后续的匹配;
  • 使用 alias 指令时,必须使用 last;
  • 使用 proxy_pass 指令时,则必须使用break。

二、Nginx 日志配置

1 nginx 日志介绍

nginx 有一个非常灵活的日志记录模式,每个级别的配置可以有各自独立的访问日志, 所需日志模块 ngx_http_log_module 的支持,日志格式通过 log_format 命令来定义,日志对于统计和排错是非常有利的,下面总结了 nginx 日志相关的配置 包括 access_loglog_formatrewrite_logerror_log

设置访问日志

access_log path [format [buffer=size] [gzip[=level]] [flush=time];

关闭访问日志

access_log off; 
  • path 指定日志的存放位置。
  • format 指定日志的格式。默认使用预定义的combined
  • buffer 用来指定日志写入时的缓存大小。默认是64k。
  • gzip 日志写入前先进行压缩。压缩率可以指定,从1到9数值越大压缩比越高,同时压缩的速度也越慢。默认是1。
  • flush 设置缓存的有效时间。如果超过flush指定的时间,缓存中的内容将被清空。
    2 log_format 指令
    Nginx 预定义了名为 combined 日志格式,如果没有明确指定日志格式默认使用该格式:
    log_format combined '$remote_addr - r e m o t e u s e r [ remote_user [ remoteuser[time_local] ’
    ‘"$request" $status KaTeX parse error: Double superscript at position 37: … '̲"http_referer" “$http_user_agent”’;

如果不想使用Nginx预定义的格式,可以通过log_format指令来自定义。
语法

log_format name [escape=default|json] string ...;
  • name 格式名称。在 access_log 指令中引用。
  • escape 设置日志书写内存方式是json还是default,默认是default
  • string 要定义的日志格式内容。该参数可以有多个。参数中可以使用Nginx变量。

log_format 指令中常用的一些变量:

$remote_addr, $http_x_forwarded_for #记录客户端IP地址
$remote_user #记录客户端用户名称
$request #记录请求的URL和HTTP协议
$status #记录请求状态
$body_bytes_sent #发送给客户端的字节数,不包括响应头的大小
$bytes_sent #发送给客户端的总字节数
$connection #连接的序列号
$connection_requests #当前通过一个连接获得的请求数量。
$msec #日志写入时间。单位为秒,精度是毫秒。
$pipe #如果请求是通过HTTP流水线(pipelined)发送,pipe值为“p”,否则为“.”。
$http_referer #记录从哪个页面链接访问过来的,可以根据该参数进行防盗链设置
$http_user_agent #记录客户端浏览器相关信息
$request_length #请求的长度(包括请求行,请求头和请求正文)。
$request_time #请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始,直到把最后一个字符发送给客户端后进行日志写入为止。
$time_iso8601 #ISO8601标准格式下的本地时间。
$time_local #通用日志格式下的本地时间。

实验

通过日志查看访问服务器的ip

代理机配置中加入

proxy_set_header X-Real-IP $remote_addr;

访问 服务器

[root@localhost ~]# curl 服务器ip
bilibili 干杯!!!

去服务器中查看日志信息

[root@localhost ~]# cat /var/log/nginx/last-break.log 
2020/12/18 02:02:17 [info] 29870#29870: *1 client 192.168.116.157 closed keepalive connection

2 error_log 指令

错误日志在Nginx中是通过error_log指令实现的。该指令记录服务器和请求处理过程中的错误信息。
语法
配置错误日志文件的路径和日志级别。

error_log file [level];
Default:
error_log logs/error.log error;
file 参数指定日志的写入位置。
level 参数指定日志的级别。level可以是debug, info, notice, warn, error, crit, alert,emerg中的任意值。可以看到其取值范围是按紧急程度从低到高排列的。只有日志的错误级别等于或高于level指定的值才会写入错误日志中。默认值是error

扩展日志级别:

debug级别:低级别,包含的信息非常详细
info级别:稍微的高一点了。用的多一些。
notice 和warning
notice:相当于提示
warning:警告 和warn 一样
err和error 一样。
crit:比较严重了
alert:告警,很严重
emerg: 恐慌级别, 级别最高的

基本用法

error_log /var/logs/nginx/nginx-error.log
配置段: http, server, location作用域。
例子中指定了错误日志的路径为:/var/logs/nginx/nginx-error.log,日志级别使用默认的 error

3 rewrite_log 指令

ngx_http_rewrite_module模块提供的。用来记录重写日志的。对于调试重写规则建议开启,启用时将在error log中记录notice级别的重写日志。
基本语法:

rewrite_log on | off;

默认值:

rewrite_log off;

配置段: http, server, location, if作用域。

4 nginx 日志配置总结

Nginx中通过access_logerror_log指令配置访问日志和错误日志,通过log_format我们可以自定义日志格式。

详细的日志配置信息可以参考Nginx官方文档

5 单独开启server的访问日志

需要:代理机与server端已经可以代理访问

首先修改代理机的配置

[root@localhost nginx]# cat /etc/nginx/nginx.conf
#user  nobody;
worker_processes  1;
events {
    
    
    worker_connections  1024;
}
http{
    
    
    server {
    
    
        listen 80;
        server_name localhost;
        location  / {
    
    
              proxy_pass http://server机IP;
              proxy_set_header X-REAl-IP $remote_addr;
            }
      }
}

server机

root@localhost ~]# cat /etc/nginx/nginx.conf 
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    
    
    worker_connections  1024;
}


http {
    
    
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_real_ip"';
    
    access_log  /var/log/nginx/access.log  main;
    
    sendfile        on;
    #tcp_nopush     on;
    
    keepalive_timeout  65;
    
    #gzip  on;
    
    include /etc/nginx/conf.d/*.conf;

}

[root@nginx-client conf.d]# nginx -s reload
[root@localhost ~]# > /var/log/nginx/http_access.log

代理机访问(或其他机访问代理机)

[root@localhost nginx]# curl 127.0.0.1
bilibili 干杯!!!

回server机查看日志

[root@localhost ~]# cat /var/log/nginx/http_access.log
192.168.116.157 - - [18/Dec/2020:08:12:18 -0500] "GET / HTTP/1.0" 200 25 "-" "curl/7.29.0" "127.0.0.1"
#最前面是代理机,最后面是访问的端口ip 是多少

6 nginx的日志轮转

[root@localhost ~]# rpm -ql nginx |grep log
/etc/logrotate.d/nginx
/var/log/nginx
[root@localhost ~]# vim /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    
          #指定需要轮转处理的日志文件
        daily               #日志文件轮转周期,可用值为: daily/weekly/yearly
        missingok           # 忽略错误信息
        rotate 7            # 轮转次数,即最多存储7个归档日志,会删除最久的归档日志
        minsize 5M          #限制条件,大于5M的日志文件才进行分割,否则不操作
        dateext             # 以当前日期作为命名格式
        compress            # 轮循结束后,已归档日志使用gzip进行压缩
        delaycompress       # 与compress共用,最近的一次归档不要压缩
        notifempty          # 日志文件为空,轮循不会继续执行
        create 640 nginx nginx     #新日志文件的权限
        sharedscripts       #有多个日志需要轮询时,只执行一次脚本
        postrotate    # 将日志文件转储后执行的命令。以endscript结尾,命令需要单独成行
                if [ -f /var/run/nginx.pid ]; then    #判断nginx的PID。# 默认logrotate会以root身份运行
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}

执行命令:

[root@192 nginx]# /usr/sbin/logrotate -f /etc/logrotate.conf

创建计划任务:

[root@192 nginx]# crontab -e
59 23 * * * /usr/sbin/logrotate -f /etc/logrotate.conf

查看压缩的日志

[root@localhost bin]# ls /var/log/nginx/
access.log  http_access.log           last-break.log
error.log   http_access.log-20201218  last-break.log-20201218

7 nginx 错误页面配置

nginx错误页面包括404 403 500 502 503 504等页面,只需要在server中增加以下配置即可:
/etc/nginx/conf.d/nginx.conf

error_page  404   /404.html;
location = /404.html {
    
    
   root   /usr/share/nginx/html;
}

注意:
/usr/share/nginx/html 路径下必须有404.html这个文件!!!

404.html上如果引用其他文件的png或css就会有问题,显示不出来,因为其他文件的访问也要做配置;
为了简单,可以将css嵌入文件中,图片用base编码嵌入;
编译文件 404.html 文件,并写入如下内容:

[root@localhost bin]# cat /usr/share/nginx/html/404.html 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
        <title>404</title>
        <style>
            .layout-table{
    
    display:table;height:100%;width:100%;vertical-align: middle;margin-top:150px}
            .layout-table-cell{
    
    display: table-cell;vertical-align: middle;text-align:center}
            .layout-tip{
    
    font-size:28px;color:#373737;margin: 0 auto;margin-top:16px;border-bottom: 1px solid #eee;padding-bottom: 20px;width: 360px;}
            #tips{font-size:18px;color:#666666;margin-top:16px;}
        </style>
    </head>
    <body class="layui-layout-body">
        <div class="layui-layout layui-layout-admin">


            <div class="layui-body">
                <div class="layout-table">
                    <div class="layout-table-cell">
                        <img src="//static.hdslb.com/error/very_sorry.png" class="layout-img">
                        <p class="layout-tip">哎呀,页面被22娘偷走啦!</p>
                        <p id="tips">请检查您的网络连接是否正常或者输入的网址是否正确</p>
                    </div>
                </div>
            </div>
        </div>
        
    </body>

</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Houaki/article/details/111401764