IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 系统运维 -> nginx常用模块 -> 正文阅读

[系统运维]nginx常用模块

一、nginx常用模块

1. Nginx目录索引

ngx_http_index_module模块找不到索引文件时,通常会将请求传递给ngx_http_autoindex_module模块。ngx_http_autoindex_module模块处理以斜杠字符/结尾的请求,并生成目录列表。

#启用或禁用目录列表输出,on开启,off关闭。
Syntax: autoindex on | off;
Default: autoindex off;
Context: http, server, location # 可以放在http server location任意位置

#指定是否应在目录列表中输出确切的文件大小,on显示字节,off显示大概单位。
Syntax: autoindex_exact_size on | off;
Default: autoindex_exact_size on;
Context: http, server, location

#指定目录列表中的时间是应以本地时区还是UTC输出。on本地时区,off UTC时间。
Syntax: autoindex_localtime on | off;
Default: autoindex_localtime off;
Context: http, server, location

1.1 配置示例

[root@web01 conf.d]# cat /etc/nginx/conf.d/bertwu.conf 
server {
	listen 80;
	server_name mirror.bertwu.com;
	charset utf-8; # 指定字符集,防止中文乱码
	autoindex on;  # 打开索引,系统找不到index.html时候自动生成索引列表而不报404错误
	autoindex_exact_size off;  # 文件以人性化单位显示,默认字节
	autoindex_localtime on; # 文件显示本地时间
	root /mirror/;
	
	location / {
		index index.html; 
	}
}

在这里插入图片描述

1.2 模拟企业内网仓库

server {
	listen 80;
	server_name mirror.bertwu.com;
	charset utf-8;
	root /mirror;
	
	location / {
		index index.html; 
	}
	# 提供yum源仓库目录
	location /repo {
		autoindex on;
		autoindex_exact_size off;
		autoindex_localtime on;
	}
}


# 首页内容
[root@web01 mirror]# cat /mirror/index.html 
<font color="red" size="14" >欢迎来到企业私有镜像站</p>
<a href="repo">点我跳转到镜像站</a>



#使用rsync同步科大园
[root@web01 mirror]# rsync -avz rsync://rsync.mirrors.ustc.edu.cn/repo/centos/ /mirror/repo/

# 将该目录创建为仓库目录
# createrepo /mirror/repo

2. Nginx访问控制

ngx_http_access_module 模块允许限制对某些客户端地址的访问。

2.1 配置语法

#允许配置语法
Syntax: allow address | CIDR | unix: | all;
Default: —
Context: http, server, location, 
limit_except

#拒绝配置语法
Syntax: deny address | CIDR | unix: | all;
Default: —
Context: http, server, location, 
limit_except

2.2 示例

  1. 只允许指定的IP能访问/centos, 其它网段全部拒绝。
[root@web01 conf.d]# cat bertwu.com.conf 
server {
	listen 80;
	server_name mirror.bertwu.com;
	charset utf-8;
	root /mirror;
	
	location / {
		index index.html; 
	}
	# 提供yum源仓库目录
	location /repo {
		autoindex on;
		autoindex_exact_size off;
		autoindex_localtime on;
		allow 10.0.0.7/32; # 只允许本机访问 /repo
		deny all; 
	}
}

在本机上直接crul
[root@web01 conf.d]# curl -H Host:mirror.bertwu.com http://10.0.0.7/repo
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>


换一台主机crul 发现报403错误(因为另一台主机的ip不是10.0.0.7)
[root@rsync ~]# curl http://10.0.0.7/repo
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

注意:deny和allow的顺序是有影响的。默认情况下,从第一条规则进行匹配如果匹配成功,则不继续匹配下面的内容。如果匹配不成功,则继续往下寻找能匹配成功的内容

3. Nginx基础认证

ngx_http_auth_basic_module模块允许使用HTTP基本身份验证,验证用户名和密码来限制对资源的访问。

3.1 配置语法

#使用HTTP基本身份验证协议启用用户名和密码验证。
Syntax: auth_basic string | off;
Default: auth_basic off;
Context: http, server, location, 
limit_except

#指定保存用户名和密码的文件
Syntax: auth_basic_user_file file;
Default: -
Context: http, server, location, 
limit_except

指定保存用户名和密码的文件,格式如下:

#可以使用htpasswd程序或"openssl passwd"命令生成对应的密码;
name1:passwd1
name2:passwd2


[root@web01 conf.d]# yum install httpd-tools
#使用htpaaswd创建新的密码文件, -c创建新文件 -b允许命令行输入密码
[root@web01 conf.d]# htpasswd -c -b /etc/nginx/ngx_passwd bertwu 123

3.2 配置示例

[root@web01 conf.d]# cat bertwu.com.conf 
server {
	listen 80;
	server_name mirror.bertwu.com;
	charset utf-8;
	root /mirror;
	
	location / {
		index index.html; 
	}
	# 提供yum源仓库目录
	location /repo {
		autoindex on;
		autoindex_exact_size off;
		autoindex_localtime on;
		#allow 10.0.0.7/32;
		#deny all;
		auth_basic "欢迎登录";
		auth_basic_user_file /etc/nginx/ngx_passwd;  # 指定密码文件路径
	}
}

访问 /repo发现已经需要密码了
在这里插入图片描述

4. Nginx限流限速

4.1 为什么要限速

限制某个用户在一定时间内能够产生的Http请求。或者说限制某个用户的下载速度。
超出限制系统会报503: 过载保护错误

4.2 限速应用场景

下载限速:限制用户下载资源的速度;ngx_http_core_module
请求限制:限制用户单位时间内所产生的Http请求数;ngx_http_limit_req_module
连接限制:限制同一时间的连接数,及并发数限制;ngx_http_limit_conn_module

4.3 请求频率限速原理

水(请求)从上方倒入水桶,从水桶下方流出(被处理);如果说水(请求)流入的过快,水桶流出(被处理)的过慢,来不及流出的水存在水桶中(缓存),然后以固定速率流出,水桶满后则水溢出(丢弃)。简单来说就是:当处理速度,达不到请求的速度,则会将请求放置缓存,然后持续处理。当缓存被沾满,如果还有大量的请求,则会被丢弃。

4.4 限制请求并发数

1.语法:

请求限制设置语法
Syntax: limit_req_zone key zone=name:size rate=rate;
Default: —
Context: http

调用语法
Syntax: limit_req zone number [burst=number] [nodelay];
Default: —
Context: http, server, location

2.基于来源IP对下载速率限制,限制每秒处理1次请求,但可以突发超过5个请求放入缓存

[root@web01 conf.d]# cat bertwu.com.conf 
# http标签中定义请求限制, rate限制速率,限制一秒钟最多一个IP请求
limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
server {
	listen 80;
	server_name mirror.bertwu.com;
	charset utf-8;
	root /mirror;
	# 请求超过1r/s,剩下的将被延迟处理,请求数超过burst定义的数量,则返回503
	limit_req zone=req_one burst=5 nodelay;
	location / {
		index index.html; 
	}
	# 提供yum源仓库目录
	location /repo {
		autoindex on;
		autoindex_exact_size off;
		autoindex_localtime on;
		#allow 10.0.0.7/32;
		#deny all;
		#auth_basic "欢迎登录";
		#auth_basic_user_file /etc/nginx/ngx_passwd; 
	}
}

语法解释:

limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
#第一个参数:$binary_remote_addr表示通过这个标识来做限制,限制同一客户端ip地址。
#第二个参数:zone=req_one:10m表示生成一个大小为10M,名为req_one的内存区域,用来存储访问的频次信息。
#第三个参数:rate=1r/s表示允许相同标识的客户端的访问频次,这里限制的是每秒1次。

limit_req zone=req_one burst=5 nodelay;
#第一个参数:zone=req_one 设置使用哪个配置区域来做限制,与上面limit_req_zone 里的name对应。

#第二个参数:burst=5,设置一个大小为5的缓冲区,当有大量请求过来时,超过了访问频次限制的请求
可以先放到这个缓冲区内。

#第三个参数:nodelay,超过访问频次并且缓冲区也满了的时候,则会返回503,如果没有设置,
则所有请求会等待排队

4.5 并发连接数限制

1.指令

Syntax: limit_conn_zone key zone=name:size;
Default: —
Context: http

Syntax: limit_conn zonename number;
Default: —
Context: http, server, location

2.设置共享内存区域和给定键值的最大允许个连接数。超过此限制时,服务器将返回503错误以回复请求

[root@web01 conf.d]# cat bertwu.com.conf 
limit_conn_zone $binary_remote_addr zone=req_od:10m; # 设定
server {
	listen 80;
	server_name mirror.bertwu.com;
	charset utf-8;
	root /mirror;
	limit_conn req_od 2;   # 调用,最大并发连接数为2,超过报503错误
	limit_rate 200k;  # 设定限速
	location / {
		index index.html; 
	}
	# 提供yum源仓库目录
	location /repo {
		autoindex on;
		autoindex_exact_size off;
		autoindex_localtime on;
		
	}
}


# 在/mirror/repo下创建bigdata文件,浏览器模拟下载此文件,由于限速,所以能够长时间保持连接
[root@web01 mirror]# dd if=/dev/zero of=/mirror/repo/bigdata bs=300M count=1

在这里插入图片描述
还可以返回指定信息

[root@web01 conf.d]# cat bertwu.com.conf 
limit_conn_zone $binary_remote_addr zone=req_od:10m;
server {
	listen 80;
	server_name mirror.bertwu.com;
	charset utf-8;
	root /mirror;
	limit_conn req_od 2;
	limit_rate 200k;
	
	# 捕获503错误,内部跳转做响应处理
	error_page 503 @temp; 
	location @temp {
		default_type text/html;
		return 200 '请联系客服充值,然后再次下载';
		}

	location / {
		index index.html; 
	}
	# 提供yum源仓库目录
	location /repo {
		autoindex on;
		autoindex_exact_size off;
		autoindex_localtime on;
		
	}
}

4.6 限制下载速度

[root@web01 conf.d]# cat bertwu.com.conf 
#limit_conn_zone $binary_remote_addr zone=req_od:10m;
server {
	listen 80;
	server_name mirror.bertwu.com;
	charset utf-8;
	root /mirror;
	#limit_conn req_od 2;
	limit_rate_after 100m; # 先不限速下载100m
	limit_rate 200k;       # 100m后速度限制为200k/s

	location / {
		index index.html; 
	}
	# 提供yum源仓库目录
	location /repo {
		autoindex on;
		autoindex_exact_size off;
		autoindex_localtime on;
	}
}

在这里插入图片描述

4.7 综合场景实践

  1. 限制web服务器请求数处理为1秒一个,触发值为5,限制用户仅可同时下载一个文件。
  2. 当下载超过100M则限制下载速度为500k
  3. 如果同时下载超过2个视频,则返回提示 “请联系管理员进行会员充值” 或 跳转到其他页面;
[root@web01 conf.d]# cat bertwu.conf
limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=req_od:10m;
server {
	listen 80;
	charset utf-8;
	server_name mirror.bertwu2.com;
	root /mirror;
	limit_rate_after 100m;
	limit_rate 500k;
	limit_req zone=req_one burst=5 nodelay;
	limit_req_status 412;
	limit_conn req_od 1;
	
	error_page 503 500 502 @error_temp;
	location @error_temp {
		default_type text_html;
		return 302 http://www.jd.com;
	} 
	 
	location / {
		index index.html;
	
	}
 	location /repo {
		autoindex on;
		autoindex_exact_size off;
		autoindex_localtime on;
	} 
}

5. nginx状态监控

ngx_http_stub_status_module模块提供对基本状态信息的访问。默认情况下不集成该模块,需要使用
--with-http_stub_status_module集成。
语法

Syntax: stub_status;
Default: —
Context: server, location

示例

[root@web01 conf.d]# cat bertwu.conf
limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=req_od:10m;
server {
	listen 80;
	charset utf-8;
	server_name mirror.bertwu2.com;
	root /mirror;
	limit_rate_after 100m;
	limit_rate 500k;
	limit_req zone=req_one burst=5 nodelay;
	limit_req_status 412;
	limit_conn req_od 1;
	
	error_page 503 500 502 @error_temp;
	location @error_temp {
		default_type text_html;
		return 302 http://www.jd.com;
	} 
	 
	location / {
		index index.html;
	
	}
 	location /repo {
		autoindex on;
		autoindex_exact_size off;
		autoindex_localtime on;
	}
	location /nginx_status {

		stub_status;
		allow 10.0.0.1/32;
		deny all;	
	}
 
}

在这里插入图片描述

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

如何理解Reading、Writing、Waiting?
假设现在有两条船分别为C 、S。C船需要 S船的1个物品,那么此时C船就要给S船发送一个消息。
1、S船收到这个消息时就是reading
2、S船将物资发送给C船,这个时候就是writing
3、如果C船需要S船很多个物品,那么需要C船和S船建立起一个物资传送管道,不断的传送物资。这个管道建立起来的时候,就是waiting状态了。

6 Nginx资源缓存

  • 浏览器缓存设置用于提高网站性能,尤其是新闻网站,图片一旦发布,改动的可能是非常小的。所以我们希望能否用户访问一次后,图片缓存在用户的浏览器长时间缓存。
  • 浏览器是有自己的缓存机制,它是基于HTTP协议缓存机制来实现的,在HTTP协议中有很多头(Headers)信息,那么实现浏览器的缓存就需要依赖特殊的头信息来与服务器进行特殊的验证,如: Expires (http/1.0) ;Cache-control (http/1.1) Nginx静态资源缓存参考

6.1 浏览器无缓存

在这里插入图片描述

6.2 浏览器有缓存

在这里插入图片描述

6.3 缓存过期校验

  1. 浏览器请求服务器会先进行Expires、Cache-Control的检查,检查缓存是否过期,如果没有过期则直接从缓存文件中读取。
  2. 如果缓存过期,首先检查是否存在etag,如果存在则会客户端会向web服务器请求if-None-Match,与etag值进行比对,由服务器决策返回200还是304。
  3. 如果etag不存在,则进行last-Modified检查,客户端会向web服务器请求If-Modified-Since,与last-Modified进行比对,由服务器决策返回200还是304。
    在这里插入图片描述深入理解浏览器缓存机制

6.4 缓存配置语法

作用: 添加Cache-Control, Expires头
Syntax: expires [modified] time;或者expires epoch | max | off;
Default: expires off;
Context: http, server, location, if in location
[root@web01 conf.d]# cat cache.conf 
server {
	listen 80;
	server_name www.bertwu.com;
	root /test;
	charset utf-8;
	location / {
	index index.html;
	
	}
	location ~ .*\.(png|jpg|jpeg|gif)$ {
		expires 1d;
	}
}

如果开发代码没有正式上线时,希望静态文件不被缓存

   location ~ .*\.(css|js|swf|json|mp4|htm|html)$ {       
   		add_header Cache-Control no-store;       
   		add_header Pragma no-cache;   
   		}
}

7. Nginx资源压缩

Nginx将发送至客户端之前的数据进行压缩,然后传输,这能够有效地节约带宽,并提高响应速度;
对图片的压缩不显著,对文本的压缩比较显著。
在这里插入图片描述

7.1 配置语法

1、启用或关闭gzip压缩
Syntax: gzip on | off;
Default: gzip off;
Context: http, server, location, if in location

2、gzip支持的压缩类型
Syntax: gzip_types mime-type ...;
Default: gzip_types text/html image/gif ; # 在/etc/nginx/mime.types文件中添加需要的类型
Context: http, server, location

3、gzip压缩比率,压缩率越高,CPU消耗越大,范围1--9
Syntax: gzip_comp_level level;
Default: gzip_comp_level 1;
Context: http, server, location

4、gzip压缩的最小文件,小于设置的值文件将不会被压缩(由"Content-Length"响应头字段确定)
Syntax: gzip_min_length length;
Default: gzip_min_length 20;
Context: http, server, location

5、gzip压缩支持的协议版本
Syntax: gzip_http_version 1.0 | 1.1;
Default: gzip_http_version 1.1;
Context: http, server, location

6、启用压缩,是否在响应报文首部插入"Vary: Accept-Encoding"
Syntax: gzip_vary on | off;
Default: gzip_vary off;
Context: http, server, location

压缩建议局部设定,因为请求的类型不同,压缩比率也会不同,所以不建议全局设定

7.2图片压缩

server {
	listen 80;
	server_name www.bertwu.com;
	root /test;
	charset utf-8;
	location / {
	index index.html;
	
	}
	location ~ .*\.(png|jpg|jpeg|gif)$ {
		expires 1d;
		gzip on;
		gzip_http_version 1.1;
		gzip_comp_level 2;
		gzip_min_length 20k;
		gzip_types image/jpeg image/gif image/png;
		gzip_vary on;
	}
}

7.3 文本文件压缩

server {
	listen 80;
	server_name www.bertwu.com;
	root /test;
	charset utf-8;
	location / {
	index index.html;
	
	}
	location ~ .*\.(txt|pdf)$ {
		gzip on;
		gzip_http_version 1.1;
		gzip_comp_level 2;
		gzip_min_length 20k;
		gzip_types text/plain application/pdf;
		gzip_vary on;
	}
}

二、 Nginx Location

2.1 什么是Location

Location用来控制访问网站的uri路径;

2.2 语法

location [ = | ~ | ~* | ^~ ] uri { ... }

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

location uri 添加 / 和不添加 / 的区别?

#不添加/,默认上/code/test目录下找index.html文件,如果没有 index.html则会查找/code/test文件
location /test {
    root /code;
    index index.html;
}
	
#添加/,默认上/test目录下寻找index.html文件,如果没有index.html 则会直接返回404 
location /test/ {
    root /code;
}

#示例测试代码
[root@web01 code]# cat /etc/nginx/conf.d/uri.oldxu.net.conf 
	server {
    listen 80;
		server_name uri.oldxu.net;
		root /code;

	#	location /test {
	#		index index.html;
	#	}

		location /test/ {
			index index.html;
		}
	}

2.3 Location优先级示例

[root@web01 conf.d]# cat location.conf 
server {
	listen 80;
	server_name location.bertwu.com;
	charset utf-8;
	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)';
	}

}

测试结果如下,建议用curl测试
1.请求 location.bertwu.com,会被location = /匹配
[root@web01 conf.d]# curl -H Host:location.bertwu.com http://10.0.0.7
location = /

2.请求 location.bertwu.com/index.html,会被location /匹配
[root@web01 conf.d]# curl -H Host:location.bertwu.com http://127.0.0.1/index.html
location /

3.请求 location.bertwu.com/documents/,会被location /documents匹配
[root@web01 conf.d]# curl -H Host:location.bertwu.com http://127.0.0.1/documents/
location /documents

4.请求 location.bertwu.com/images/1.gif,会被location ^~ /images匹配
[root@web01 conf.d]# curl -H Host:location.bertwu.com http://172.16.1.7/images/1.gif
location ^~ /images


5.请求 location.bertwu.com/documents/1.jpg,会被location ~* \.(gif|jpg|jpeg)匹配,因为 /documents 这种匹配是通用匹配,优先级低
root@web01 conf.d]# curl -H Host:location.bertwu.com http://172.16.1.7/documents/1.jpg
location ~* \.(gif|jpg|jpeg)

2.4 应用场景示例

[root@web01 conf.d]# cat location1.conf 
server {
	listen 80;
	server_name location1.bertwu.com;
	charset utf-8;
	root /code;
	# 通用匹配,任何请求都会匹配到
	location / {
		index index.html;
	}
	# 精准匹配,必须请求的uri是/nginx_status才返回服务器状态
	location = /nginx_status {
		stub_status;
	}
	# 严格区分大小写,匹配以.php结尾的都走这个location 
	location ~ \.php$ {
		default_type text/html;
		return 200 'php访问成功';
	}
	# 严格区分大小写,匹配以.jsp结尾的都走这个location
	location ~ \.jps$ {
		default_type text/html;
		return 200 'jps访问成功';
	}
	# 不区分大小写匹配,只要用户访问.jpg,gif,png,js,css 都走这条location
	location ~* \.(gif|jpg|jpeg|css)$ {
		expires 3d;
		default_type text/html;
		return 200 'location ~* \.(gif|jpg|jpeg)';
	}
	# 不区分大小写匹配,禁止访问下面内容	
	location ~* \.(sql|bak|tgz|tar.gz|.git)$ {
		deny all;
	}

}

模拟浏览器访问结果
[root@web01 code]# curl -H Host:location1.bertwu.com http://127.0.0.1/nginx_status
Active connections: 1 
server accepts handled requests
 218 218 234 
Reading: 0 Writing: 1 Waiting: 0

[root@web01 code]# curl -H Host:location1.bertwu.com http://127.0.0.1/1.php
php访问成功

 [root@web01 code]# curl -H Host:location1.bertwu.com http://127.0.0.1/1.jps
jps访问成功

[root@web01 code]# curl -H Host:location1.bertwu.com http://127.0.0.1/1.jpg
location ~* \.(gif|jpg|jpeg)


[root@web01 code]# curl -H Host:location1.bertwu.com http://127.0.0.1/1.git
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

2.5 Location @重定向

location @name 这样的location不用于常规请求处理,而是用于内部重定向。
重定向有两种方式

1.重定向到指定的页面
error_page 404 /error.html 表示跳转到指定页面 /表示root指定的路径

2.error_page 404 @error_404 表示跳转到内部location 可以返回页面,也可以跳转到具体页面。

1.跳转到自定义页面

[root@web01 conf.d]# cat error.conf 
server {
	listen 80;
	server_name error.test.com;
	root /error;
	charset utf-8;
	location / {
		index index.html;
	}
	error_page 400 403 404 /error.html;
}

[root@web01 conf.d]# mkdir /error
[root@web01 conf.d]# echo "首页" > /error/index.html
[root@web01 conf.d]# echo "我是自定义错误页面" > /error/error.html

[root@web01 conf.d]# curl -H Host:error.test.com http://127.0.0.1
首页

[root@web01 conf.d]# curl -H Host:error.test.com http://127.0.0.1/asdfsff
我是自定义错误页面
  1. 返回文本文字
[root@web01 conf.d]# cat error.conf 
server {
	listen 80;
	server_name error.test.com;
	root /error;
	charset utf-8;
	location / {
		index index.html;
	}
	error_page 400 403 404 @error;
	location @error {
	 	default_type text/html;
		return 200 '糟糕,页面不小心走丢了!';
	}
}

  1. 跳转到首页或其他页面
[root@web01 conf.d]# cat error.conf 
server {
	listen 80;
	server_name error.test.com;
	root /error;
	charset utf-8;
	location / {
		index index.html;
	}
	error_page 400 403 404 @error;
	location @error {
	 	default_type text/html;
		return 302 http://$server_name; 
		#return 302 http://error.test.com;
		#return 302 http://www.jd.com; # 跳转到京东
	}
}

三、 Nginx 日志模块

Nginx的日志记录非常灵活,可以通过log_format来定义格式。

3.1 日志格式语法

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

# 默认Nginx定义语法格式如下
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
access_log  /var/log/nginx/access.log  main; # 声明

示例:
root@web01 ~]# tail -1 /var/log/nginx/access.log
10.0.0.1 - - [14/Aug/2021:16:56:26 +0800] "GET /dsfsdf HTTP/1.1" 302 145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36" "-"



可以自定义日志格式
log_format test  '$remote_addr - $remote_user [$time_local] "$request" '                      '$status';
/var/log/nginx/access_test.log test; # 声明

3.2 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头信息中,
 增加http_x_forwarded_for信息,用来记录客户端IP地址和客户端请求的服务器地址。

3.3 Nginx访问日志

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

如果服务器有多个站点server ,应该对每个server配置对应的日志,而不应该在location中配置日志,因为没必要。如果把所有站点日志配置在http中会显得特别混乱。

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

示例

http {
	 access_log /var/log/nginx/access.log main;  # http层全局log所有都会记录这里
	 server {
		 access_log /var/log/nginx/bertwu1.log main  # 站点1的日志路径
		 location / {
		 	...
		 }
	}
	 server {
		 access_log /var/log/nginx/bertwu2.log main  # 站点2的日志路径
		 location / {
		 }
		 location /admin {
			.....
		}
	}
}

日志记录规则,先局部,后全局,局部若定义了日志,只在局部生效,否则往上层找,直到找到为止。location层定义了,就在location层,否则去server层,如果这两层都没定义,就去找http层。

3.4 Nginx错误日志

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

Nginx错误日志示例

error_log /var/log/nginx/error.log warn;
# 关闭错误日志error_log /dev/null;

3.5 Nginx日志过滤

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

#请求favicon.ico时,不记录日志
location /favicon.ico {   
	access_log off;
	expires 365d;   
	return 200;
}

#当有人访问gif、png等资源时,将日志丢入空
location ~* .*\.(gif|jpg|png|css|js)$ {
   access_log /dev/null;
}
  系统运维 最新文章
配置小型公司网络WLAN基本业务(AC通过三层
如何在交付运维过程中建立风险底线意识,提
快速传输大文件,怎么通过网络传大文件给对
从游戏服务端角度分析移动同步(状态同步)
MySQL使用MyCat实现分库分表
如何用DWDM射频光纤技术实现200公里外的站点
国内顺畅下载k8s.gcr.io的镜像
自动化测试appium
ctfshow ssrf
Linux操作系统学习之实用指令(Centos7/8均
上一篇文章      下一篇文章      查看所有文章
加:2021-08-15 15:58:38  更:2021-08-15 16:00:11 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/21 1:24:47-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码