# Nginx 常用模块

# 1. Nginx 安装部署

# 1.1 安装 Nginx 方式

安装 Nginx 软件的方式有很多种,分为如下几种

  • 源码编译 =>Nginx (1. 版本随意 2. 安装复杂 3. 升级繁琐)
  • epel 仓库 =>Nginx (1. 版本较低 2. 安装简单 3. 配置不易读)
  • 官方仓库 =>Nginx (1. 版本较新 2. 安装简单 3. 配置易读,强烈推荐
# 1.2 安装 Nginx 依赖
[root@web01 ~]# yum install -y gcc gcc-c++ autoconf pcre pcre-devel make automake httpd-tools
# 1.3 配置 Nginx 源

官网 https://nginx.org -> 点击 download -> 点击 Pre-Built Packages-> 点击 stable and mainline -> 选择系统 RHEL and derivatives

[root@web01 ~]# cat /etc/yum.repos.d/nginx.repo 
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
# 1.4 安装 Nginx 服务
[root@web01 ~]# yum install nginx -y
[root@web01 ~]# systemctl start nginx && systemctl enable nginx
# 1.5 检查 Nginx 版本
# 检查版本
[root@web01 ~]# nginx -v
nginx version: nginx/1.26.1
# 检查编译参数
[root@web01 ~]# nginx -V

# 2. Nginx 目录结构

#1.Nginx 主配置文件
/etc/nginx/conf.d/default.conf    #默认网站配置文件
/etc/nginx/nginx.conf             #nginx 主配置文件
#2.Nginx 代理配置文件
/etc/nginx/fastcgi_params         #Fastcgi 代理配置文件
/etc/nginx/scgi_params            #scgi 代理配置文件
/etc/nginx/uwsgi_params           #uwsgi 代理配置文件
#3.Nginx 编码配置文件
/etc/nginx/mime.types             #Content-Type 与扩展名
#4.Nginx 管理命令文件
/usr/sbin/nginx                   #Nginx 命令行管理终端工具
/usr/sbin/nginx-debug             #Nginx 命令行与终端调试工具
#5.Nginxx 日志相关文件
/var/log/nginx                    #Nginx 默认存放日志目录
/etc/logrotate.d/nginx            #Nginx 默认的日志切割

# 3. Nginx 基本配置

[root@web01 ~]# egrep -v '^#|^$' /etc/nginx/nginx.conf 
user  nginx;              #nginx 的运行身份为 nginx 用户     
worker_processes  auto;   #启动的 worker 进程数量
error_log  /var/log/nginx/error.log notice;      #错误日志的路径
pid        /var/run/nginx.pid;  #存储进程的 pid
events {
    worker_connections  1024;        #一个 worker 最大连接数,worker_connections * worker_processes = 最大链接数
}
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_forwarded_for"';  #定义日志的格式
    access_log  /var/log/nginx/access.log  main;   #访问日志
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;         #长连接超时时间
    #gzip  on;
    include /etc/nginx/conf.d/*.conf;     #包含的子文件
}

# 4. Nginx 虚拟主机

Nginx 配置虚拟主机有如下三种方式

  • 1、基于主机多 IP 方式
  • 2、基于端口的配置方式
  • 3、基于多个 hosts 名称方式 (多域名方式
# 4.1 基于多 IP 虚拟主机实践
[root@web01 ~]# cat /etc/nginx/conf.d/address.conf
server {
	...
	listen 10.0.0.7:80;
	...
}
server {
	...
	listen 172.16.1.7:80;
	...
}
# 4.2 基于多端口虚拟主机实践
[root@web01 ~]# cat /etc/nginx/conf.d/port1.conf
server {
	...
	listen 80;
	...
}
[root@web01 ~]# cat /etc/nginx/conf.d/port2.conf
server {
	...
	listen 81;
	...
}
# 4.3 基于多域名虚拟主机实践
[root@web01 ~]# echo "server1" > /code/server1/index.html
[root@web01 ~]# echo "server2" > /code/server2/index.html
[root@web01 ~]# cat /etc/nginx/conf.d/server1.conf
server {
		listen 80;
		server_name server1.oldxu.net;
		
		root /code/server1;
		index index.html;
...
}
[root@web01 ~]# cat /etc/nginx/conf.d/server2.conf
server {
		...
		listen 80;
		server_name server2.oldxu.net;
		root /code/server2;
		index index.html;
}

# 5. Nginx 常用模块

# 5.1 Nginx 目录索引

当 ngx_http_index_module 模块找不到索引文件时,通常会将请求传递给 ngx_http_autoindex_module 模块。

ngx_http_autoindex_module 模块处理以斜杠字符 ('/') 结尾的请求,并生成目录列表。

# 5.1.1 配置语法
#启用或禁用目录列表输出,on 开启,off 关闭。
Syntax: autoindex on | off;
Default: autoindex off;
Context: 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
# 5.1.2 配置示例
[root@web01 conf.d]# cat mirrors.hmallleasing.com.conf
server {
	listen 80;
	server_name mirrors.hmallleasing.com;
	charset utf-8; #设定字符集,防止中文字符乱码显示
	root /mirrors;
	location / {
	        index index.html;
	}
	location /repo {
	        autoindex on;  #目录索引
	        autoindex_exact_size off;  #显示单位
                autoindex_localtime on;    #指定目录列表中的时间是应以本地时区
	}
}
[root@web01 conf.d]# mkdir /mirrors/repo -p
[root@web01 conf.d]# echo "欢迎访问 mirrors 镜像站点!!!" > /mirrors/index.html
[root@web01 repo]# ll
-rw-r--r-- 1 root root 31367480 Aug 23 21:05 EVCapture_v4.2.3.exe
-rw-r--r-- 1 root root  1885872 Aug 23 21:05 Everything-1.4.1.1023.x64-Setup.exe
-rw-r--r-- 1 root root 31456728 Aug 23 21:09 PixPin_1.7.5.0.exe
[root@web01 ~]# nginx -t
[root@web01 ~]# systemctl reload nginx

1.jpg

# 5.2 Nginx 访问控制

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

# 5.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
# 5.2.2 配置示例
[root@web01 conf.d]# cat mirrors.hmallleasing.com.conf 
server {
	listen 80;
	server_name mirrors.hmallleasing.com;
	charset utf-8; #设定字符集,防止中文字符乱码显示
	root /mirrors;
	location / {
	        index index.html;
	}
	location /repo {
	        autoindex on;  #目录索引
	        autoindex_exact_size off;  #显示单位
            autoindex_localtime on;    #指定目录列表中的时间是应以本地时区
		    #访问控制
		    allow 192.168.40.1/32;
		    deny all;
	}
}
[root@web01 conf.d]# nginx -t
[root@web01 conf.d]# systemctl reload nginx
[root@web01 conf.d]# curl -HHost:mirrors.hmallleasing.com http://192.168.40.7/repo/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.26.1</center>
</body>
</html>

注意 **:deny allow** 的顺序是有影响的

  • 默认情况下,从第一条规则进行匹配
  • 如果匹配成功,则不继续匹配下面的内容。
  • 如果匹配不成功,则继续往下寻找能匹配成功的内容。
# 5.3 Nginx 基础认证

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

# 5.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
#使用 htpaaswd 创建新的密码文件,-c 创建新文件 -b 允许命令行输入密码
[root@oldxu ~]# yum install httpd-tools
[root@oldxu ~]# htpasswd -b -c /etc/nginx/auth_conf xuyong 123456
# 5.3.2 配置示例
[root@web01 conf.d]# cat mirrors.hmallleasing.com.conf
server {
	listen 80;
	server_name mirrors.hmallleasing.com;
	charset utf-8; #设定字符集,防止中文字符乱码显示
	root /mirrors;
	location / {
	        index index.html;
	}
	location /repo {
	        autoindex on;  #目录索引
	        autoindex_exact_size off;  #显示单位
            autoindex_localtime on;    #指定目录列表中的时间是应以本地时区
		    #访问控制
		    allow 192.168.40.1/32;
		    deny all;
		    #basci 认证,局部生效 
		    auth_basic "welcome to auth_basic";
		    auth_basic_user_file auth_conf;
	}
}
[root@web01 conf.d]# nginx -t
[root@web01 conf.d]# systemctl reload nginx
# 5.4 Nginx 限流限速
# 5.4.1 为什么要限速

限制某个用户在一定时间内能够产生的 Http 请求。或者说限制某个用户的下载速度。

# 5.4.2 限速应用场景

下载限速:限制用户下载资源的速度;

ngx_http_core_module

请求限制:限制用户单位时间内所产生的 Http 请求数;

ngx_http_limit_req_module

连接限制:限制同一时间的连接数,及并发数限制;

ngx_http_limit_conn_module

# 5.4.3 限制请求并发数

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 个请求放入缓存区

# http 标签段定义请求限制,rate 限制速率,限制一秒钟最多一个 IP 请求 $remote_addr; $binary_remote_addr
http {
	limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
}
server {
		listen 80;
		server_name mirror.oldxu.net;
		# 请求超过 1r/s, 剩下的将被延迟处理,请求数超过 burst 定义的数量,则返回 503
		limit_req zone=req_one burst=3 nodelay;
		
		location / {
			root /code;
			index index.html;
		}
}
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=3 nodelay;
#第一个参数:zone=req_one 设置使用哪个配置区域来做限制,与上面 limit_req_zone 里的 name 对应。
#第二个参数:burst=3,设置一个大小为 3 的缓冲区,当有大量请求过来时,超过了访问频次限制的请求可以先放到这个缓冲区内。
#第三个参数:nodelay,超过访问频次并且缓冲区也满了的时候,则会返回 503,如果没有设置,则所有请求会等待排队。

3. 配置示例

[root@web01 ~]# cat /etc/nginx/conf.d/mirrors.hmallleasing.com.conf 
#http 标签段定义请求限制,rate 限制速率,限制一秒钟最多一个 IP 请求,10m 可以存储 10*1024*1024/4=2,621,440 个 IP
limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
server {
	listen 80;
	server_name mirrors.hmallleasing.com;
	charset utf-8; #设定字符集,防止中文字符乱码显示
	root /mirrors;
	# 请求超过 1r/s, 剩下的将被延迟处理,请求数超过 burst 定义的数量 3,则返回 503
	limit_req zone=req_one burst=5 nodelay;
	limit_req_status 500; # 请求限制状态码,默认返回 503
	location / {
	        index index.html;
	}
	location /repo {
	        autoindex on;  #目录索引
	        autoindex_exact_size off;  #显示单位
            autoindex_localtime on;    #指定目录列表中的时间是应以本地时区
		    #访问控制
			allow 192.168.40.1/32;
			deny all;
			#basci 认证,局部生效 
			auth_basic "welcome to auth_basic";
			auth_basic_user_file auth_conf;
	}
}
[root@web01 ~]# nginx -t
[root@web01 ~]# systemctl reload nginx
# 5.4.5 限制并发连接数

1. 指令

Syntax: limit_conn_zone key zone=name:size;
Default: —
Context: http
Syntax: limit_conn zone number;
Default: —
Context: http, server, location

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

[root@web01 ~]# cat /etc/nginx/conf.d/mirrors.hmallleasing.com.conf 
#http 标签段定义连接限制
limit_conn_zone $binary_remote_addr zone=conn_od:10m;
server {
	listen 80;
	server_name mirrors.hmallleasing.com;
	charset utf-8; #设定字符集,防止中文字符乱码显示
	root /mirrors;
	#限制最大并发数为 20
	limit_conn conn_od 20;
	#出现 503 错误,跳转到充值中心
	error_page 503 @errpage;
	location @errpage {
		default_type text/html;
		return 302 https://vip.qq.com;
	}
	location / {
	        index index.html;
	}
	location /repo {
	        autoindex on;  #目录索引
	        autoindex_exact_size off;  #显示单位
            autoindex_localtime on;    #指定目录列表中的时间是应以本地时区
			#访问控制
			allow 192.168.40.1/32;
			deny all;
			#basci 认证,局部生效 
			auth_basic "welcome to auth_basic";
			auth_basic_user_file auth_conf;
	}
}
[root@web01 ~]# nginx -t
[root@web01 ~]# systemctl reload nginx
[root@web01 mirrors]# dd if=/dev/zero of=/mirrors/bigdata bs=500M count=1
# 5.4.6 限制下载速度
[root@web01 mirrors]# cat /etc/nginx/conf.d/mirrors.hmallleasing.com.conf 
server {
	listen 80;
	server_name mirrors.hmallleasing.com;
	charset utf-8; #设定字符集,防止中文字符乱码显示
	root /mirrors;
	#达到 100m 开始限速
	limit_rate_after 100m; 
	#限速 100K
	limit_rate 100k;
	#出现 503 错误,跳转到充值中心
	error_page 503 @errpage;
	location @errpage {
		default_type text/html;
		return 302 https://vip.qq.com;
	}
	location / {
	        index index.html;
	}
	location /repo {
	        autoindex on;  #目录索引
	        autoindex_exact_size off;  #显示单位
            autoindex_localtime on;    #指定目录列表中的时间是应以本地时区
			#访问控制
			allow 192.168.40.1/32;
			deny all;
			#basci 认证,局部生效 
			auth_basic "welcome to auth_basic";
			auth_basic_user_file auth_conf;
	}
}
# 5.4.7 综合场景实践
  • 1、限制 web 服务器请求数处理为 1 秒一个,触发值为 5、限制用户仅可同时下载一个文件;
  • 2、当下载超过 100M 则限制下载速度为 500k;
  • 3、如果同时下载超过 2 个视频,则返回提示 "请联系 oldxu 进行会员充值" | 跳转到其他页面;
[root@web01 mirrors]# cat /etc/nginx/conf.d/mirrors.hmallleasing.com.conf 
limit_req_zone $binary_remote_addr zone=req_one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=conn_od:10m;
server {
	listen 80;
	server_name mirrors.hmallleasing.com;
	root /mirrors;
	# 请求超过 1r/s, 剩下的将被延迟处理,请求数超过 burst 定义的数量 5,则返回 503
	limit_req zone=req_one burst=5 nodelay;
	#限制最大并发数为 2
	limit_conn conn_od 1;
	#达到 100m 开始限速
	limit_rate_after 100m; 
	#限速 100K
	limit_rate 500k;
	#出现 503 错误,跳转到充值中心
	error_page 503 @errpage;
	location @errpage {
		default_type text/html;
		return 302 https://vip.qq.com;
	}
	location / {
	        index index.html;
	}
}
[root@web01 mirrors]# 
[root@web01 mirrors]# nginx -t
[root@web01 mirrors]# systemctl reload nginx
# 5.5 Nginx 状态监控

ngx_http_stub_status_module 模块提供对基本状态信息的访问。

默认情况下不集成该模块,需要使用 --with-http_stub_status_module 集成。

# 5.5.1 配置语法
Syntax: stub_status;
Default: —
Context: server, location
# 5.5.2 配置示例
[root@web01 mirrors]# cat /etc/nginx/conf.d/mirrors.hmallleasing.com.conf 
server {
	listen 80;
	server_name mirrors.hmallleasing.com;
	location / {
	        index index.html;
	}
	location /nginx_status {
		stub_status;
        #访问控制
        allow 192.168.40.1/32;
        deny all;
	}
}
[root@web01 mirrors]# nginx -t
[root@web01 mirrors]# systemctl reload nginx
# 5.5.3 页面状态

此配置创建一个简单的网页,其基本状态数据可能如下所示

[root@web01 mirrors]# curl -HHost:mirrors.hmallleasing.com http://192.168.40.7/nginx_status
Active connections: 1 
server accepts handled requests
 20 20 42 
Reading: 0 Writing: 1 Waiting: 0 
# Active connections:当前活跃连接数,包括 Waiting 等待连接数。
# accepts: 已接收的总 TCP 连接数量。
# handled: 已处理的 TCP 连接数量。
# requests: 当前总 http 请求数量。
# Reading: 当前读取的请求头数量。
# Writing: 当前响应的请求头数量。
# Waiting: 当前等待请求的空闲客户端连接数。
[root@web01 mirrors]# curl -s -HHost:mirrors.hmallleasing.com http://192.168.40.7/nginx_status|awk -F ':' 'NR==1 {print $NF}'
# 5.6 Nginx 资源压缩

Nginx 将发送至客户端之前的数据进行压缩,然后传输,这能够有效地节约带宽,并提高响应速度;

# 5.6.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;
Context: http, server, location
# 3、gzip 压缩比率,压缩率越高,CPU 消耗越大 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
# 5.6.2 图片压缩案例
[root@web01 ~]# mkdir -p /code/images
[root@web01 conf.d]# cat static.hmallleasing.com.conf
server {
	listen 80;
	server_name static.hmallleasing.com;
	root /code/images;
	
	location ~* .*\.(jpg|gif|png)$ {
			gzip on;
			gzip_http_version 1.1;
			gzip_comp_level 2;
			gzip_min_length 10k;
			gzip_types image/jpeg image/gif image/png;
			gzip_vary on;
	}
}
[root@web01 conf.d]# nginx -t
[root@web01 conf.d]# systemctl reload nginx
# 5.6.3 文件压缩案例
[root@web01 ~]# mkdir -p /code/doc
[root@web01 conf.d]# cat static.hmallleasing.com.conf
server {
	listen 80;
	server_name static.hmallleasing.com;
	root /code/doc;
	
	location ~ .*\.(txt|pdf)$ {
			gzip on;
			gzip_http_version 1.1;
			gzip_comp_level 2;
			gzip_min_length 10k;
			gzip_types text/plain application/pdf;;
			gzip_vary on;
	}
}
[root@web01 conf.d]# nginx -t
[root@web01 conf.d]# systemctl reload nginx
# 5.7 Nginx Location

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

# 5.7.1 Location 语法示例
location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
/api/xxx/dadas/dsadsa
/apiv1/dsa/dsaxx/sadsa/
# 匹配符 匹配规则 优先级
# = 精确匹配 1
# ^~ 以某个字符串开头 2
# ~ 区分大小写的正则匹配 3
# ~* 不区分大小写的正则匹配 4
# / 通用匹配,任何请求都会匹配到 5
# 5.7.2 Location 优先级示例
[root@web01 conf.d]# cat location.hmallleasing.com.conf
server {
	listen 80;
	server_name location.oldxu.net;
	
	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. 请求 http://location.hmallleasing.com/ 会被 location =/ 匹配
#2. 请求 http://location.hmallleasing.com/index.html 会被 location / 匹配
#3. 请求 http://location.hmallleasing.com/documents/1.html 会被 location /documents/ 匹配
#4. 请求 http://location.hmallleasing.com/images/1.gif 会被 location ^~ /images/ 匹配
#5. 请求 http://location.hmallleasing.com/documents/1.jpg 会被 location ~* \.(gif|jpg|jpeg)$ 匹配
# 5.7.3 Location 应用场景
[root@web01 conf.d]# cat location2.hmallleasing.com.conf 
server {
	listen 80;
	server_name location2.hmallleasing.com;
        charset utf-8;
	
	# 通用匹配,任何请求都会匹配到
	location / {
		root html;
		index index.html;
	}
	
	# 精准匹配,必须请求的 uri 是 /nginx_status
	location = /nginx_status {
		stub_status;
	}
	
	# 严格区分大小写,匹配以.php 结尾的都走这个 location info.php
	location ~ \.php$ {
		default_type text/html;
		return 200 'php访问成功';
	}
	
	# 严格区分大小写,匹配以.jsp 结尾的都走这个 location
	location ~ \.jsp$ {
		default_type text/html;
		return 200 'jsp访问成功';
	}
	
	# 不区分大小写匹配,只要用户访问.jpg,gif,png,js,css 都走这条 location
	location ~* \.(jpg|gif|png|js|css)$ {
		# return 403;
		expires 3d;
	}
	
	# 不区分大小写匹配
	location ~* \.(sql|bak|tgz|tar.gz|.git)$ {
		deny all;
		default_type text/html;
		return 200 '禁止访问!!!';
	}
}
# 5.7.4 Location @重定向
[root@web01 conf.d]# cat location3.hmallleasing.com.conf 
server {
	listen 80;
	server_name location3.hmallleasing.com;
	root /code;
	
	location / {
		index index.html;
	}
    #error_page 400 403 404 error.html;
	#如果出现异常,则重新定向到 @error_404 这个 location 上
	error_page 404 @error_404;
	location @error_404 {
		default_type text/html;
	#	return 200 ' 你可能是不小心走丢了。';
		return 302 http://$server_name;
	}
}
# 5.8 Nginx 日志模块

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

# 5.8.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"';
log_format test '$remote_addr - $remote_user [$time_local] "$request" '$status';
log_format test '$remote_addr - $remote_user [$time_local] "$request" '
				'$status ';
#access_log
/var/log/nginx/access.log main;
#access_log
/var/log/nginx/access_test.log test;

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 地址和客户端请求的服务器地址。
# 5.8.2 Nginx 访问日志

1.web 服务器的访问日志是非常重要的,我们可以通过访问日志来分析用户的访问情况,也可以通过访问日志发现一些异常访问。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
http {
	access_log /var/log/nginx/access.log main;
	
    server {
    }
    server {
            access_log /var/log/nginx/test.hmallleasing.com.log main;
            
            location / {
   				access_log /var/log/nginx/test.hmallleasing.com.log main;
            }
            location /admin {
            }
    }
}

2.Nginx 访问日志配置示例

server {
		listen 80;
		server_name log.hmallleasing.com;
		# 将当前的 server 网站的访问日志记录至对应的目录,使用 main 格式
		access_log /var/log/nginx/log.hmallleasing.com.log main;
		
		location / {
				root /code;
				index index.html;
		}
}
# 5.8.3 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;
# 5.8.4 Nginx 日志过滤

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

#请求 favicon.ico 时,不记录日志
location /favicon.ico {
		access_log off;
		return 200;
}
#或,当有人访问 gif、png 等资源时,将日志丢入空
location ~* .*\.(gif|jpg|png|css|js)$ {
		access_log /dev/null;
}
此文章已被阅读次数:正在加载...更新于

请我喝[茶]~( ̄▽ ̄)~*

Xu Yong 微信支付

微信支付

Xu Yong 支付宝

支付宝