Day54-nginx限速-访问日志-错误日志精讲

测试请求限制

[root@web01 conf.d]# ab -n100 -c4  http://mirrors.etiantian.org/centos/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking mirrors.etiantian.org (be patient).....done

Server Software:        nginx/1.20.1
Server Hostname:        mirrors.etiantian.org
Server Port:            80

Document Path:          /centos/
Document Length:        9134 bytes

Concurrency Level:      4
Time taken for tests:   0.014 seconds
Complete requests:      100
Failed requests:        94
   (Connect: 0, Receive: 0, Length: 94, Exceptions: 0)
Write errors:           0
Non-2xx responses:      94
Total transferred:      91722 bytes
HTML transferred:       73322 bytes
Requests per second:    7263.22 [#/sec] (mean)
。。。。
 100%      1 (longest request)

#失败94个,有94个状态码非2XX
Failed requests:        94
Non-2xx responses:      94

ab,jemeter,webbanch,tcpcopy,http_runner

压测:不错的文章
链接: https://www.imooc.com/article/291715

连接限制(limit_conn)

http {
    limit_conn_zone $binary_remote_addr zone=addr:10m;
    server {
    location /download/ {
        limit_conn addr 1;
        }
    }

下载速度限制(limit_rate) ngx_http_core_module

location /flv/ {
    flv;
    limit_rate_after 500k;
    limit_rate       50k;
}

综合配置

[root@web01 conf.d]# cat mirrors.etiantian.org.conf
limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
    listen 80;
    server_name mirrors.etiantian.org;
    charset utf-8;
    root /data;   #正常站点目录
location / {
    index index.html; #阿里云镜像首页
    }

#yum仓库目录
location /centos/ {
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;
    #allow 10.0.0.7;        #允许单个IP地址
    #allow 10.0.0.0/24;     #允许地址或地址段
    #deny all;	           #拒绝所有
  
    #deny 10.0.0.7;      #拒绝指定的地址或地址段
    #deny 10.0.0.0/24;      #拒绝指定的地址或地址段
    #allow all;          #允许所有的地址
    #限制请求为r/s,有5个进入队列,多余的丢弃。
    #limit_req zone=req_one burst=5 nodelay;
    #限制并发连接为1
     limit_conn addr 1;
    #限制下载速度
    limit_rate_after 50m;  #生产场景:VIP体验,类似百度云体验VIP下载达到50m,开始限速
    limit_rate 200k;       #限制速度为200K
}
 location /admin/ {           #网站后台,先进行办公源地址访问。
    #用户名密码验证
    auth_basic "oldboyedu Auth access";
    auth_basic_user_file /etc/nginx/auth_pass;
    #来源IP限制
    #allow 10.0.0.7;           #允许指定的地址或地址段
    #deny all;                 #拒绝所有的地址
    }
}

nginx -t && systemctl reload nginx

测试:
1.搞一个大文件

dd if=/dev/zero of=/data/centos/oldboy.zip bs=1M count=500

2.测试方法

[root@web01 conf.d]# curl -o a.zip http://mirrors.etiantian.org/centos/oldboy.zip
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
 59  100M   59 59.9M    0     0  1199k      0  0:01:25  0:00:51  0:00:34  202k

3.ab压测方法:指定大文件,坑:不要测试简单Html文件。

[root@web01 conf.d]# ab -n10 -c2  http://mirrors.etiantian.org/centos/oldboy.zip
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking mirrors.etiantian.org (be patient).....done


Server Software:        nginx/1.20.1
Server Hostname:        mirrors.etiantian.org
Server Port:            80

Document Path:          /centos/oldboy.zip
Document Length:        197 bytes

Concurrency Level:      2
Time taken for tests:   0.014 seconds
Complete requests:      10
Failed requests:        1
   (Connect: 0, Receive: 0, Length: 1, Exceptions: 0)
Write errors:           0
Non-2xx responses:      9
Total transferred:      104861305 bytes
HTML transferred:       104859373 bytes
Requests per second:    277.09 [#/sec] (mean)
Time per request:       7.218 [ms] (mean)
Time per request:       3.609 [ms] (mean, across all concurrent requests)
Transfer rate:          2837529.94 [Kbytes/sec] received
  99%     36
 100%     36 (longest request)
说明:
#当前Non-2xx responses: 9,表示有9个请求不是2xx状态码,被Nginx服务器拒绝,一共是10个并发。

上节课后作业解答:

[root@web01 conf.d]# cat mirrors.etiantian.org.conf
limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    listen 80;
    server_name mirrors.etiantian.org;
    charset utf-8;
    root /data;   #阿里云镜像正常站点目录
location / {
    index index.html; #阿里云镜像首页
    }

#yum仓库centos目录
location /centos/ {
    autoindex on;
    allow 10.0.0.0/24;     #允许地址或地址段
    deny all;	           #拒绝所有

    #限制请求为r/s,有5个进入队列,多余的丢弃。
    #limit_req zone=req_one burst=5 nodelay;
	
    #限制并发连接为1
     limit_conn addr 1;
	
    #限制下载速度
    limit_rate_after 50m;  #生产场景:VIP体验,类似百度云体验VIP下载达到50m,开始限速
    limit_rate 200k;       #限制速度为200K
}
 location /admin/ {           #网站后台,先进行办公源地址访问。
    #用户名密码验证
    auth_basic "oldboyedu Auth access";
    auth_basic_user_file /etc/nginx/auth_pass;
	
    #来源IP限制
    allow 10.0.0.0/24;           #允许指定的地址或地址段
    deny all;                    #拒绝所有的地址
    }
}

1.Nginx状态监控

1.1 Nginx status介绍

Nginx软件的功能模块中有一个ngx_http_stub_status_module模块,这个模块的主要功能是记录Nginx的基本访问状态信息,让使用者了解Nginx的工作状态,例如:连接数等信息。

1.2 Nginx status配置

用location的方式实现状态信息配置,例如在任意一个虚拟主机里,为server标签增加如下配置:

location /nginx_status {
    stub_status;
    access_log off;
    allow 10.0.0.0/24; #<==设置允许和禁止的IP段访问。
    deny all;          #<==设置允许和禁止的IP段访问。
}

[root@web01 conf.d]# cat mirrors.etiantian.org.conf
limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
    listen 80;
    server_name mirrors.etiantian.org;
    charset utf-8;
    root /data;   #正常站点目录
    access_log  /var/log/nginx/mirrors.etiantian.org.access.log.gz  main gzip=9 buffer=32k flush=5s;
location / {
    index index.html; #阿里云镜像首页
}

#yum仓库目录
location /centos/ {
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;
    #allow 10.0.0.7;        #允许单个IP地址
    #allow 10.0.0.0/24;     #允许地址或地址段
    #deny all;	           #拒绝所有
  
    #deny 10.0.0.7;      #拒绝指定的地址或地址段
    #deny 10.0.0.0/24;      #拒绝指定的地址或地址段
    #allow all;          #允许所有的地址
    #限制请求为r/s,有5个进入队列,多余的丢弃。
    #limit_req zone=req_one burst=5 nodelay;
    #限制并发连接为1
     limit_conn addr 1;
    #限制下载速度
    limit_rate_after 50m;  #生产场景:VIP体验,类似百度云体验VIP下载达到50m,开始限速
limit_rate 200k;       #限制速度为200K
}
 location /admin/ {           #网站后台,先进行办公源地址访问。
    #用户名密码验证
    auth_basic "oldboyedu Auth access";
    auth_basic_user_file /etc/nginx/auth_pass;
    #来源IP限制
    #allow 10.0.0.7;           #允许指定的地址或地址段
    #deny all;                 #拒绝所有的地址
}
location /nginx_status {
    stub_status;
    }
}

结尾的就是nginx状态的配置:

   location /nginx_status {
        stub_status;
    }	

1.3 基本状态数据如下所示:(注意本地解析域名)

[root@web01 conf.d]# curl http://mirrors.etiantian.org/nginx_status
Active connections: 1  # 表示nginx正在处理的活动连接数1个
server accepts handled requests
 397 397 4046 
Reading: 0 Writing: 1 Waiting: 0 

1.4 状态信息说明

状态含义
Active connections当前活跃连接数,包括Waiting等待连接数。
accepts已接收的总TCP连接数量。
handled已处理的TCP连接数量。
requests当前总http请求数量。
Reading当前读取的请求头数量。
Writing当前响应的请求头数量。
Waiting当前等待请求的空闲客户端连接数

Zabbix监控Nginx状态信息 https://www.cnblogs.com/bixiaoyu/p/9169319.html

2.Nginx location

2.1 location作用

location指令作用是可以根据用户请求URI来执行不同的应用,URI的知识前面章节已经讲解过,其实就是根据用户请求的网站的地址URL匹配,匹配成功即进行相关的操作。

2.2 location语法

  location [ = | ~ | ~* | ^~ ]      uri            { ... }
#  指令         匹配标识            匹配的网站网址   匹配URI后要执行的配置段
location @name { ... }

# 匹配符 匹配规则                  优先级
# =     精确匹配                     1 
# ^~    以某个字符串开头              2
# ~     区分大小写的正则匹配           3
# ~*    不区分大小写的正则匹配         4
# /     通用匹配,任何请求都会匹配到    5

2.3 location优先级示例

[root@web01 conf.d]# cat location01.etiantian.org.conf 
server {
	listen 80;
	server_name location01.etiantian.org;
location = / {
	default_type text/html;
	return 200 'location = /';
}

location / {
	default_type text/html;
	return 200 'location /';
}

location /documents/ {
	default_type text/html;
	return 200 'location /documents/';
}

location ^~ /images/ {
	default_type text/html;
	return 200 'location ^~ /images/';
}

location ~* \.(gif|jpg|jpeg)$ {
	default_type text/html;
	return 200 'location ~* \.(gif|jpg|jpeg)';
    }
}

2.4 匹配顺序实践:

#(1)等号精确匹配优先,no.1
[root@web01 conf.d]# curl http://location01.etiantian.org/
location = / 
#(2)# ^~ ,以某个字符串开头no.2
[root@web01 conf.d]# curl http://location01.etiantian.org/images/1.gif
location ^~ /images/

#(3)~*    不区分大小写的正则匹配 
[root@web01 conf.d]# curl http://location01.etiantian.org/documents/1.jpg
location ~* \.(gif|jpg|jpeg)

#(4)#目录匹配
[root@web01 conf.d]# curl http://location01.etiantian.org/documents/1.html
location /documents/ #目录匹配

#(5) / 通用匹配,任何请求都会匹配到no.5
[root@web01 conf.d]# curl http://location.etiantian.org/index.html
location /   #默认匹配最后。

2.5 location02 @name,这样的location02不用于常规请求处理,而是用于重定向。

[root@web01 conf.d]# cat location02.etiantian.org.conf 
server {
	listen 80;
	server_name location02.etiantian.org;
    root /data;
#如果出现如下状态码,则重新从定向到@error_status
error_page 404 403 502 @error_status
	location @error_status {
	default_type text/html;
	return 200 '你的访问出了问题,我是oldboy.';
}

[root@web01 conf.d]# curl -H "host:location02.etiantian.org" http://10.0.0.7/oldboy
你的访问出了问题,我是oldboy.

3.Nginx 日志模块

3.1 Nginx日志格式

1.log_format定义日志格式语法

#配置语法: 包括: error.log access.log
Syntax: log_format name [escape=default|json] string ...;
Default: log_format combined "...";
Context: http

2.默认Nginx定义语法格式如下

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

3.Nginx日志格式中常用的变量

$remote_addr        # 记录客户端IP地址
$remote_user        # 记录客户端用户名
$time_local         # 记录通用的本地时间
$time_iso8601       # 记录ISO8601标准格式下的本地时间
$request            # 记录请求的方法以及请求的http协议
$status             # 记录请求状态码(用于定位错误信息)
$body_bytes_sent    # 发送给客户端的资源字节数,不包括响应头的大小
$bytes_sent         # 发送给客户端的总字节数
$msec               # 日志写入时间。单位为秒,精度是毫秒。
$http_referer       # 记录从哪个页面链接访问过来的
$http_user_agent    # 记录客户端浏览器相关信息
$http_x_forwarded_for #记录客户端IP地址
$request_length     # 请求的长度(包括请求行, 请求头和请求正文)。
$request_time       # 请求花费的时间,单位为秒,精度毫秒

# 注:如果Nginx位于负载均衡器,nginx反向代理之后, web服务器无法直接获取到客 户端真实的IP地址。
# $remote_addr获取的是反向代理的IP地址。 反向代理服务器在转发请求的http头信息中,
# 增加X-Forwarded-For信息,用来记录客户端IP地址和客户端请求的服务器地址。

真实的日志内容为:

10.0.0.1- - [05/Apr/2015:12:16:00 +0800] "GET / HTTP/1.1" 200 25 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36" "-"

对应说明:

  • $remote_addr对应的真实日志里的10.0.0.100,即客户端的IP。
  • $remote_user对应的是第二个中杠“-”,没有远程用户,所以用“-”填充。
  • [$time_local]对应的是[05/Apr/2015:12:16:00 +0800]。
  • “$request"对应的是"GET / HTTP/1.1”。
  • $status对应的是200状态码,200是正常访问。
  • $body_bytes_sent对应的是25字节,响应body的大小。
  • “$http_referer"对应的是”-",直接打开的域名浏览,因此,referer没有值。
  • “$http_user_agent"对应的是"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36”。
  • “$http_x_forwarded_for"对应的是”-“,因为Web服务没有使用代理,因此此处为”-"。

3.2 Nginx访问日志

web服务器的访问日志是非常重要的,我们可以通过访问日志来分析用户的访问情况,也可以通过访问日志发现一些异常访问。

3.2.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

3.2.2 Nginx访问日志配置例

server {
    listen 80;
    server_name mirrors.etiantian.org;
    #将当前的server网站的访问日志记录至对应的目录,使用main格式
    #access_log /var/log/nginx/mirrors.etiantian.org.log main;
	access_log  /var/log/nginx/mirrors.etiantian.org.access.log.gz  main gzip=9 buffer=32k flush=5s;
location / {
    root /data;
    index index.html;
    }
}

3.2.3 Nginx日志过滤

一个网站会包含很多元素,尤其是有大量的图片、js、css等静态资源。这样的请求其实可以不用记录日志。

# 访问静态资源gif、png等时,将日志丢入空
location ~* .*\.(gif|jpg|png|css|js)$ 
{
    access_log /dev/null;
}

3.2.4 Nginx访问日志轮询切割

为什么Nginx访问日志轮询切割?
1.按天好进行相关分析。
2.单个日志过大。

方法1:00点

mv access.log  $(date +%F -d '-1d').accss.log
systemctl reload nginx
=============================================

[root@web01 scripts]# cat cut_nginx_log.sh 
#!/bin/sh
Dateformat=`date +%Y%m%d -d -1day`
Nginxlogdir="/var/log/nginx/"

Logname="mirrors.etiantian.org.access.log.gz"

#第一关
[ -d $Nginxlogdir ] && cd $Nginxlogdir||exit 1

#第二关 
[ -f $Logname ]||exit 1

#第三关
/bin/mv $Logname ${Dateformat}_$Logname

#第四关
systemctl reload nginx

# 每天00点00分进行日志滚动
#####
00 00 * * *  /bin/sh /server/scripts/cut_nginx_log.sh &>/dev/null

方法2:logrotate工具切割

/etc/logrotate.d/nginx
[root@web01 scripts]# cat  /etc/logrotate.d/nginx
/var/log/nginx/*.log.gz {
        daily
        dateext
        missingok
        rotate 52
        #compress
        delaycompress
        notifempty
        create 640 nginx adm
        sharedscripts
        postrotate
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}

#每天00点00分进行日志滚动
#crontab -e
00 00 * * *  /usr/sbin/logrotate -f /etc/logrotate.d/nginx &>/dev/null

3.3 Nginx错误日志

3.3.1 Nginx错误日志级别

常见的错误日志级别有debug | info | notice | warn | error | crit | alert | emerg
级别越高记录的信息越少,如果不定义,默认级别为error.
它可以配置在main、http、server、location段里

3.3.2 Nginx错误日志示例

error_log  /var/log/nginx/error.log crit;
#如果要想彻底关闭error_log,需要这样配置error_log /dev/null;

建议:放到http区段就可以。

4. nginx错误码原因以及解决方案

链接: http://www.laoseng.net/articles/2014/12/18/1418884520679.html

4.1 400 bad request错误的原因和解决办法

配置nginx.conf相关设置如下.

client_header_buffer_size 16k;
large_client_header_buffers 4 64k;

根据具体情况调整,一般适当调整值就可以。

4.2 Nginx 502 Bad Gateway错误

proxy_next_upstream error timeout invalid_header http_500 http_503;

或者尝试设置:

large_client_header_buffers 4 32k;

4.3 Nginx出现的413 Request Entity Too Large错误

这个错误一般在上传文件的时候会出现,
编辑Nginx主配置文件Nginx.conf,找到http{}段,添加

client_max_body_size 10m; //设置多大根据自己的需求作调整.

如果运行php的话这个大小client_max_body_size要和php.ini中的如下值的最大值一致或者稍大,这样就不会因为提交数据大小不一致出现的错误。

post_max_size = 10M
upload_max_filesize = 2M

4.4 解决504 Gateway Time-out(nginx)

遇到这个问题是在升级discuz论坛的时候遇到的

一般看来, 这种情况可能是由于nginx默认的fastcgi进程响应的缓冲区太小造成的, 这将导致fastcgi进程被挂起, 如果你的fastcgi服务对这个挂起处理的不好, 那么最后就极有可能导致504 Gateway Time-out

现在的网站, 尤其某些论坛有大量的回复和很多内容的, 一个页面甚至有几百K。

默认的fastcgi进程响应的缓冲区是8K, 我们可以设置大点

在nginx.conf里, 加入: fastcgi_buffers 8 128k

这表示设置fastcgi缓冲区为8×128k

当然如果您在进行某一项即时的操作, 可能需要nginx的超时参数调大点,例如设置成60秒:send_timeout 60;

只是调整了这两个参数, 结果就是没有再显示那个超时, 可以说效果不错, 但是也可能是由于其他的原因, 目前关于nginx的资料不是很多, 很多事情都需要长期的经验累计才有结果.

  • 29
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值