高性能Web服务器-- Nginx 核心配置详解

1.1 配置文件说明

nginx 官方帮助文档:http://nginx.org/en/docs/

Nginx的配置文件的组成部分:

  • 主配置文件:nginx.conf
  • 子配置文件: include conf.d/*.conf
  • fastcgi(php), uwsgi(python),cgi等协议相关的配置文件
  • mime.types:支持的mime类型,MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型
    • MIME消息能包含文本、图像、音频、视频以及其他应用程序专用的数据,是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。

1.1.1 Nginx 配置文件格式说明

配置文件由指令与指令块构成
每条指令以;分号结尾,指令与值之间以空格符号分隔
可以将多条指令放在同一行,用分号分隔即可,但可读性差,不推荐
指令块以{ }大括号将多条指令组织在一起,且可以嵌套指令块
include语句允许组合多个配置文件以提升可维护性
使用#符号添加注释,提高可读性
使用$符号使用变量
部分指令的参数支持正则表达式

1.1.2 Nginx 主配置文件的配置指令方式

directive value [value2 ...];
注意
(1) 指令必须以分号结尾
(2) 支持使用配置变量
内建变量:由Nginx模块引入,可直接引用
自定义变量:由用户使用set命令定义,格式: set variable_name value;
引用变量:$variable_name

1.1.3 Nginx的主配置文件结构

主配置文件结构:四部分

main block:主配置段,即全局配置段,对http,mail都有效

# 事件驱动相关的配置
event {
	...
}

# http/https 协议相关配置段
http {
	...
}

# 默认配置文件不包括下面两个块
# mail 协议相关配置段
mail {
	...
}

#	stream 服务器相关配置段
stream {
	...
}

1.1.4 Nginx默认配置文件nginx.conf的文件格式说明

文件路径:/usr/local/nginx/conf/nginx.conf

# 全局配置端,对全局生效,主要设置nginx的启动用户/组,启动的工作进程数量,工作模式,Nginx的PID路径,日志路径等。
user nginx nginx;
worker_processes 1; 	# 启动工作进程数数量
events { 				# events #设置快,主要影响nginx服务器与用户的网络连接,比如是否允许同时接受						   多个网络连接,使用哪种事件驱动模型
						# 处理请求,每个工作进程可以同时支持的最大连接数,是否开启对多工作进程下的网络						  连接进行序列化等。
  worker_connections 1024;#设置单个nginx工作进程可以接受的最大并发,作为web服务器的时候最大并发数为
							# worker_connections *worker_processes,作为反向代理的时候为
							# (worker_connections * worker_processes)/2
}
http { 		#http块是Nginx服务器配置中的重要部分,缓存、代理和日志格式定义等绝大多数功能和第三方模块都 
			# 可以在这设置,http块可以包含多个server块,而一个server块中又可以包含多个location块,
			# server块可以配置文件引入、MIME-Type定义、日志自定义、是否启用sendfile、连接超时时间和 
			# 单个链接的请求上限等。
	include mime.types;
	default_type application/octet-stream;
	sendfile on; 				# 作为web服务器的时候打开sendfile加快静态文件传输,指定是否使用
								# sendfile系统调用来传输文件
							  # sendfile系统调用在两个文件描述符之间直接传递数据(完全在内核中操作)
					#从而避免了数据在内核缓冲区和用户缓冲区之间的拷贝,操作效率很高,被称之为零拷贝,
					# 硬盘 >> kernel buffer (快速拷贝到kernelsocketbuffer) >>协议栈。
	keepalive_timeout 65; 		# 长连接超时时间,单位是秒
server { 			# 设置一个虚拟机主机,可以包含自己的全局快,同时也可以包含多个location模块
					# 比如本虚拟机监听的端口、本虚拟机的名称和IP配置,多个server 可以使用一个端口比					   如都使用 #80端口提供web服务
	listen 80; 			# 配置server监听的端口
	server_name localhost;# 本server的名称,当访问此名称的时候nginx会调用当前serevr内部的配置进程匹配。
	location / { 		# location其实是server的一个指令,为nginx服务器提供比较多而且灵活的指令
						# 都是在location中体现的,主要是基于nginx接受到的请求字符串
						# 对用户请求的UIL进行匹配,并对特定的指令进行处理
						# 包括地址重定向、数据缓存和应答控制等功能都是在这部分实现
						# 另外很多第三方模块的配置也是在location模块中配置。
		root html; 		# 相当于默认页面的目录名称,默认是安装目录的相对路径,可以使用绝对路径配置。
		index index.html index.htm; # 默认的页面文件名称
	}
	error_page 500 502 503 504 /50x.html; # 错误页面的文件名称
	location = /50x.html { 				  # location处理对应的不同错误码的页面定义到/50x.html
									  	  # 这个跟对应其server中定义的目录下。
		root html; # 定义默认页面所在的目录
	}
}

# 和邮件相关的配置
# mail {
# 	...
# } mail 协议相关配置段
# tcp代理配置,1.9版本以上支持
# stream {
# 	...
# } stream 服务器相关配置段
# 导入其他路径的配置文件
# include /apps/nginx/conf.d/*.conf
}

1.2 全局配置

Main 全局配置段常见的配置指令分类

  • 正常运行必备的配置
  • 优化性能相关的配置
  • 用于调试及定位问题相关的配置
  • 事件驱动相关的配置

1.2.1全局配置说明:

文件路径:/usr/local/nginx/conf/nginx.conf

user nginx nginx; 					# 启动Nginx工作进程的用户和组
worker_processes [number | auto]; 	# 启动Nginx工作进程的数量,一般设为和CPU核心数相同

worker_cpu_affinity 00000001 00000010 00000100 00001000 | auto ;
#将Nginx工作进程绑定到指定的CPU核心,默认Nginx是不进行进程绑定的,绑定并不是意味着当前nginx进程独占以一核心CPU,但是可以保证此进程不运行在其他核心上,这就极大减少了nginx的工作进程在不同的cpu核心上的来回跳转,减少了CPU对进程的资源分配与回收以及内存管理等,因此可以有效的提升nginx服务器的性能。

# worker绑定到cpu
CPU MASK: 00000001:0号CPU
		  00000010:1号CPU
		  ...
		  10000000:7号CPU
		  
#错误日志记录配置
语法:error_log file [debug | info | notice | warn | error | crit | alert | emerg]

#error_log logs/error.log;
#error_log logs/error.log notice;
error_log /usr/local/nginx/logs/error.log error;

# pid文件保存路径
pid /usr/local/nginx/logs/nginx.pid;
worker_priority 0; 			# 工作进程优先级,-20~20(19)
worker_rlimit_nofile 65536; # 所有worker进程能打开的文件数量上限,
							# 包括:Nginx的所有连接(例如与代理服务器的连接等)
							# 而不仅仅是与客户端的连接
							# 另一个考虑因素是实际的并发连接数不能超过系统级别的最大打开文件数的限制
							# 最好与ulimit -n 或者limits.conf的值保持一致
							
daemon off;				 	# 前台运行Nginx服务用于测试、docker等环境。
master_process off|on; 		# 是否开启Nginx的master-worker工作模式,仅用于开发调试场景,默认为on

events {
	worker_connections 65535; # 设置单个工作进程的最大并发连接数
	use epoll; 				  #	使用epoll事件驱动,
							  # Nginx支持众多的事件驱动,
							  # 比如:select、poll、epoll,只能在events模块中设置
							   
	accept_mutex on; 		  # on为同一时刻一个请求轮流由work进程处理,
							  # 而防止被同时唤醒所有worker
							  # 避免多个睡眠进程被唤醒的设置,默认为off
							  # 新请求会唤醒所有worker进程,此过程也称为"惊群"
							  # 因此nginx刚安装完以后要进行适当的优化。建议设置为on
							  
	multi_accept on; 		  # on时Nginx服务器的每个工作进程可以同时接受多个新的网络连接
							  # 此指令默认为off,
							  # 即默认为一个工作进程只能一次接受一个新的网络连接
							  # 打开后几个同接受多个。建议设置为on
}

1.2.2 全局配置参数优化调整

# 开启自动定义的工作进程及将工作进程绑定到CPU核心
[root@nginx ~]# grep -c ^processor /proc/cpuinfo      # 通过查看CPU的详细信息文件来确定几核心
	2
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
user  nobody;                  -- 修改指定的用户
worker_processes auto;         -- 修改为自动开启多核心进程
worker_cpu_affinity 0001 0010; -- 添加双核绑定进程

[root@nginx ~]# nginx -s reload
[root@nginx ~]# ps aux | grep nginx
root       47973  0.0  0.2  10008  3644 ?        Ss   13:28   0:00 nginx: master process nginx
nobody     48057  0.0  0.2  13904  4968 ?        S    15:05   0:00 nginx: worker process
nobody     48058  0.0  0.2  13904  4968 ?        S    15:05   0:00 nginx: worker process
root       48061  0.0  0.1 221680  2284 pts/0    S+   15:06   0:00 grep --color=auto nginx

1.2.3 实现Nginx的高并发配置

1.# 查看当前用户的所有资源限制
[root@nginx ~]# ulimit -a       [root@nginx ~]# sudo -u nginx ulimit -n    
1024                -- 表示 nginx 用户可以同时打开 1024 个文件或网络连接

在这里插入图片描述

2.# 对当前系统允许的最大文件连接数进行压力测试
[root@nginx ~]# dnf install httpd-tools -y     # 安装httpd-tools工具用于压力测试
# 默认配置不支持高并发
[root@nginx ~]# ab -c 5000 -n 10000 http://172.25.254.60/      -- IP为nginx的IP
# ulimit -c 并发请求数   -n  请求总数 ;压力测试时并发请求数不能大于请求总数
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 172.25.254.60 (be patient)
socket: Too many open files (24)            -- 警告访问的文件数量太多

3.# 设置允许的最大文件描述数
# 临时
[root@Nginx ~]# ulimit -n 100000  # 临时将当前会话中用户可以打开的最大文件描述符数限制设置为100000

# 永久
[root@nginx ~]# vim /etc/security/limits.conf
# End of file
nginx            -       nofile          100000 # 设置十万个最大文件连接数

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
events {
    worker_connections  100000; # 设置十万个最大并发连接数
    use epoll; 				    # 使用epoll事件驱动
}
[root@nginx ~]# nginx -s reload

[root@nginx ~]# sudo -u nginx ulimit -n
100000

# 再次测试,实现高并发
[root@nginx ~]#  ab -c 5000 -n 10000 http://172.25.254.60/
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 172.25.254.60 (be patient)
Completed 1000 requests
. . . . . .

1.3 HTTP配置块

#在响应报文中将指定的文件扩展名映射至MIME对应的类型
include /etc/nginx/mime.types;
default_type application/octet-stream; #除mime.types中的类型外
#指定其它文件的默认MIME类型,浏览器一般会提示下载

# 内容在/usr/local/nginx/conf/mime.types中
types {
text/html html;
image/gif gif;
image/jpeg jpg;
}

案例:识别php文件为text/html

[root@nginx ~]# vim /usr/local/nginx/html/haha.php   # 创建一个 .php文件
<?php
  phpinfo();    -- 加一个简单的 PHP 脚本来显示 PHP 信息(使用 phpinfo() 函数)。
?>

[root@nginx ~]# curl -I 172.25.254.60/haha.php
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Sun, 18 Aug 2024 09:22:23 GMT
Content-Type: application/octet-stream          -- 默认的文件处理
Content-Length: 22
Last-Modified: Sun, 18 Aug 2024 09:22:01 GMT
Connection: keep-alive
ETag: "66c1bd39-16"
Accept-Ranges: bytes

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
    default_type text/html;      --修改default_type指令,将其设置为text/html
    	-- ginx无法自动检测或匹配请求的文件类型时,会默认将响应的Content-Type设置为text/html。
    
[root@nginx ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

[root@nginx ~]# nginx -s reload
[root@nginx ~]# curl -I 172.25.254.60/haha.php
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Sun, 18 Aug 2024 11:53:04 GMT
Content-Type: text/html                 -- php文件正确地显示为 text/html
Content-Length: 22
Last-Modified: Sun, 18 Aug 2024 09:22:01 GMT
Connection: keep-alive
ETag: "66c1bd39-16"
Accept-Ranges: bytes

1.4 Nginx的核心配置

基于不同的IP、不同的端口以及不同域名实现不同的虚拟主机,依赖于核心模块ngx_http_core_module实现。

1.4.1 新建一个PC web站点

# 定义子配置文件路径
[root@nginx ~]# mkdir -p /usr/local/nginx/conf.d
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
    #gzip  on;
    include "/usr/local/nginx/conf.d/*.conf";     # 在配置文件的最后面添加此行
												  # 注意不要放在最前面,会导致前面的命令无法生效
# 创建虚拟主机网站配置
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf      
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;
}
[root@nginx ~]# mkdir -p /data/web/html
[root@nginx ~]# echo www.haha.org > /data/web/html/index.html
[root@nginx ~]# nginx -s reload

# 在访问主机中设地址解析
[root@nginx ~]# cat /etc/hosts
172.25.254.60 www.haha.org

# 测试
[root@nginx ~]# curl www.haha.org
www.haha.org

在windows中进行地址解析,若为普通用户下编写文件后无法保存,这是需要对普通用户进行提权才能

Windows的hosts文件路径C: /Windows/System32/drivers/etc

在这里插入图片描述

在访问主机中设地址解析

在这里插入图片描述

访问测试:

在这里插入图片描述

1.4.2 root与alias

root:指定web的家目录,在定义location的时候,文件的绝对路径等于 root+location

alias:定义路径别名,会把访问的路径重新定义到其指定的路径,文档映射的另一种机制;仅能用于location上下文,此指令使用较少

root示例:

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;
    location /test1{               -- 添加root模块
        root /data/web;            -- 注意该真实地址为/data/web/test1
    }
}
[root@nginx ~]# mkdir -p /data/web/test1
[root@nginx ~]# echo /data/web/test1 > /data/web/test1/index.html
[root@nginx ~]# nginx -s reload

测试:

在这里插入图片描述

alias示例:

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;
    location /test1{
        root /data/web;
    }
    location /test2{            # 添加alias模块
        alias /data/web/test1;  # 相当于建立软链到/data/web/test1
        					# 注意about后不要加/
							#使用alias的时候uri后面如果加了斜杠,则下面的路径配置必须加斜杠,否则403
    }
}
[root@nginx ~]# nginx -s reload

测试:

在这里插入图片描述

location中使用root指令和alias指令的意义不同

  • root #给定的路径对应于location中的/uri左侧的/

  • alias #给定的路径对应于location中的/uri的完整路径

1.4.3 location 的详细使用

  • 在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;

  • ngnix会根据用户请求的URI来检查定义的所有location,按一定的优先级找出一个最佳匹配,而后应用其配置在没有使用正则表达式的时候,nginx会先在server中的多个location选取匹配度最高的一个uri

  • uri是用户请求的字符串,即域名后面的web文件路径然后使用该location模块中的正则url和字符串,如果匹配成功就结束搜索,并使用此location处理此请求。

#语法规则:
location [ = | ~ | ~* | ^~ ] uri { ... }

=  		# 用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并立即处理请求
^~ 		# 用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头
		# 对uri的最左边部分做匹配检查,不区分字符大小写
		
~ 		# 用于标准uri前,表示包含正则表达式,并且区分大小写
~* 		# 用于标准uri前,表示包含正则表达式,并且不区分大写
不带符号 # 匹配起始于此uri的所有的uri
\ 		# 用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号

# 匹配优先级从高到低: 
(~ | ~*) , 不带符号 , ^~ , = 

location优先级:(location ~,~* 正则顺序) > (/)  >(location 完整路径) > (location 部分起始路径) > (location ^~ 路径) >(location =)

1.4.3.1 匹配案例–精确匹配(=)

在server部分使用location配置一个web界面

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80; 
    server_name www.haha.org;
    root /data/web/html;
    index index.html;

    
    location /test {
        root /data/web;
    }   
    
    location = /test {          -- 添加精确匹配
        root /data/web;
    }   

}

[root@nginx ~]# mkdir /data/web/test
[root@nginx ~]# echo test page > /data/web/test/index.html
[root@nginx ~]# nginx -s reload

访问测试:

在这里插入图片描述

1.4.3.2 匹配案例 – 以**开头的uri(^~)-- URI开始

用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头;对uri的最左边部分做匹配检查,不区分字符大小写

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;

    location ^~ /t{          -- 添加匹配以t开头的location
        root /data/web1;
    }
}
[root@nginx ~]# nginx -s reload

[root@nginx ~]# mkdir -p /data/web1/{test,test1,haha}
[root@nginx ~]# echo test web1  /data/web1/test/index.html 
[root@nginx ~]# echo /data/web1/test1 >  /data/web1/test1/index.html 
[root@nginx ~]# echo /data/web1/haha >  /data/web1/haha/index.html

访问测试:

访问t开头的uri

在这里插入图片描述

访问不是t开头的uri,出现404

在这里插入图片描述

1.4.3.3 匹配案例 – 区分大小写(~)

~ 实现区分大小写的模糊匹配. 以下范例中,

如果访问uri中包含大写字母的logo.PNG,则以下location匹配logo.png条件不成功

因为 ~ 区分大小写,当用户的请求被执行匹配时发现location中定义的是小写的png,

本次访问的uri匹配失败,后续要么继续往下匹配其他的location(如果有),要么报错给客户端

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;

    location ~ \.html$ {       -- 添加以html为结尾的uri
        root /data/web1;
    }
}
[root@nginx ~]# nginx -s reload

访问测试:

在这里插入图片描述

1.4.3.4 匹配案例 – 不区分大小写(~*)

~* 用来对用户请求的uri做模糊匹配,uri中无论都是大写、都是小写或者大小写混合,此模式也都会匹

配,通常使用此模式匹配用户request中的静态资源并继续做下一步操作,此方式使用较多

注意:此方式中,对于Linux文件系统上的文件仍然是区分大小写的,如果磁盘文件不存在,仍会提示404

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;

    location ~* \.HTML$ {  -- 添加以大写HTML为结尾的uri,在访问你测试时,不区分大小
        root /data/web1;
    }
}
[root@nginx ~]# nginx -s reload

访问测试:

在这里插入图片描述

1.4.3.5 匹配案例 – 文件名后缀

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;

    location ~* \.(HTML|ax)$ {    -- 多个不同的结尾    
        root /data/web1;
    } 
}
[root@nginx ~]# nginx -s reload
[root@nginx ~]# echo ovo >  /data/web1/haha/index.ax

默认已知的MIMME类型:(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js|css)

测试:

当访问以 .ax 结尾的 URI 时,该文件扩展名没有被映射到已知的 MIME 类型,Nginx 会将其视为二进制文件并提示下载。可以通过手动设置 MIME 类型或修改文件处理方式,避免这种情况。

在这里插入图片描述

1.4.3.6 生产中使用案例

#直接匹配网站根会加速Nginx访问处理
location = /index.html {
		......;
}

location / {
		......;
}

#静态资源配置方法1
location ^~ /static/ {
		......;
}

#静态资源配置方法2,应用较多
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
		......;
}
#多应用配置
location ~* /app1 {
		......;
}
location ~* /app2 {
		......;
}

1.4.4 Nginx 的用户认证

Nginx下的用户认证由 ngx_http_auth_basic_module 模块提供此功能

1.# 创建Nginx的用户
[root@nginx ~]# htpasswd -cm /usr/local/nginx/.htpasswd admin   #使用htpasswd来创建第一个用户
		# -c 参数:用于创建新的 .htpasswd 文件。如果文件已经存在,它会被覆盖。
		# -m 参数:使用 MD5 加密密码。
New password: 
Re-type new password: 
Adding password for user admin

[root@nginx ~]# htpasswd -m /usr/local/nginx/.htpasswd xiaoming  # 创建第二个用户
New password: 
Re-type new password: 
Adding password for user xiaoming
[root@nginx ~]# cat /usr/local/nginx/.htpasswd        # 查看Nginx的用户管理文件,创建两个用户成功
admin:$apr1$.TVuPH5J$9K0ozanmMtYOlC6BYYZ7E.
xiaoming:$apr1$cQw6MK.j$t5hAj4HmvCJizkqJfzL4q/

2.# 创建新的发布目录
[root@nginx ~]# mkdir /data/web/pgp
[root@nginx ~]# echo OvO > /data/web/pgp/index.html

3.# 配置location
[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name www.haha.org;
	root /data/web/html;
	index index.html;
	
	location /pgp {
		root /data/web;	
		auth_basic "login password !!!";
		auth_basic_user_file "/usr/local/nginx/.htpasswd"; 
	}
}
[root@nginx ~]# nginx -s reload

# Linux访问测试
[root@nginx ~]# curl www.haha.org/pgp/ -u admin:123
OvO
[root@nginx ~]# curl www.haha.org/pgp/ -u xiaoming:123
OvO

浏览器访问测试:
在这里插入图片描述

1.4.5 自定义错误页面(sorry page)

自定义错误页,同时也可以用指定的响应状态码进行响应, 可用位置:http, server, location, if in location

error_page code ... [=[response]] uri;

示例:

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;
    error_page 404 /40x.html;    # 自定义一个错误页面

    location /pgp {
        root /data/web;
        auth_basic "login password !!!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }

    location = /40x.html{                   # 添加自定义错误页面的location
        root /data/web/errorpage;
    }
}

[root@nginx ~]# mkdir -p /data/web/errorpage
[root@nginx ~]# echo error page > /data/web/errorpage/40x.html
[root@nginx ~]# nginx -s reload

# 测试
[root@nginx ~]# curl www.haha.org/testa
error page

访问不存在的页面进行测试:

在这里插入图片描述

1.4.6 自定义错误日志

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;
    error_page 404 /40x.html;
    error_log /var/log/haha.org/error.log;               -- 自定义错误日志
    access_log /var/log/haha.org/access.log;             -- 自定义日志

    location /pgp {
        root /data/web;
        auth_basic "login password !!!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }

    location = /40x.html{
        root /data/web/errorpage;
    }
}
[root@nginx ~]# mkdir -p /var/log/haha.org  
[root@nginx ~]# nginx -s reload      

# 测试
# 访问存在的页面进行测试并验证是在指定目录生成新的日志文件
[root@nginx ~]# curl www.haha.org 
www.haha.org
[root@nginx ~]# cat /var/log/haha.org/access.log                # 查看日志
172.25.254.60 - - [19/Aug/2024:16:40:36 +0800] "GET /testa HTTP/1.1" 404 11 "-" "curl/7.76.1"

# 访问不存在的页面进行测试并验证是在指定目录生成新的日志文件
[root@nginx ~]# curl www.haha.org/testa     
error page
[root@nginx ~]# cat /var/log/haha.org/error.log
2024/08/19 16:40:36 [error] 49933#0: *252347 open() "/data/web/html/testa" failed (2: No such file or directory), client: 172.25.254.60, server: www.haha.org, request: "GET /testa HTTP/1.1", host: "www.haha.org"

1.4.7 检测文件是否存在

try_files会按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如果所有文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误。

语法格式:

Syntax: try_files file ... uri;
try_files file ... =code;
Default: —
Context: server, location

示例:

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;
    error_page 404 /40x.html;
    error_log /var/log/haha.org/error.log;
    access_log /var/log/haha.org/access.log;
    try_files $uri $uri.html $uri/index.html /error/default.html;    -- 添加try_files检测
    # 依次检测,当检测完都不存在,会报500错误!!
    
    location /pgp {
        root /data/web;
        auth_basic "login password !!!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }

    location = /40x.html{
        root /data/web/errorpage;
    }
}
[root@nginx ~]# nginx -s reload

# 访问测试:
# 当检测完都不存在以上定义的文件格式时,出现500错误
[root@nginx ~]# curl www.haha.org
<html>
<head><title>500 Internal Server Error</title></head>
<body>
<center><h1>500 Internal Server Error</h1></center>
<hr><center>nginx/1.26.2</center>
</body>
</html>

# 如果不存在页面, 就转到default.html页面
[root@nginx ~]# mkdir /data/web/html/error
[root@nginx ~]# echo error default > /data/web/html/error/default.html
[root@nginx ~]# curl www.haha.org
error default

1.4.8 长连接配置

在主配置文件中进行设定

keepalive_timeout timeout [header_timeout]; # 设定保持连接超时时长,0表示禁止长连接,默认为75s
											# 通常配置在http字段作为站点全局配置
keepalive_requests 数字; 					   # 在一次长连接上所允许请求的资源的最大数量
											# 默认为100次,建议适当调大,比如:500
											
		

示例:

1.# 下载长连接测试工具
[root@nginx ~]# dnf install telnet -y

2.# 设定主配置文件的长连接
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
	. . .
	#keepalive_timeout  0;
    keepalive_timeout  65 60;
    # 开启长连接后,返回客户端的会话保持时间为60s,单次长连接累计请求达到指定次数请求或65秒就会被断开,第		二个数字60为发送给客户端应答报文头部中显示的超时时间设置为60s:如不设置客户端将不显示超时时间。
    # 相当于Keep-Alive:timeout=60 
    #浏览器收到的服务器返回的报文#如果设置为0表示关闭会话保持功能,将如下显示:
	#Connection:close 浏览器收到的服务器返回的报文
	
    keepalive_requests 2;   # 设置最大连接次数为2
    . . .
[root@nginx ~]# nginx -s reload

3.# 使用telnet命令测试
[root@nginx ~]# curl -v www.haha.org   -- 使用curl -v(小写)来查看http的请求报文头部,用于测试
*   Trying 172.25.254.60:80...
* Connected to www.haha.org (172.25.254.60) port 80 (#0)
> GET / HTTP/1.1             -- 用于输入下面测试中的报头
> Host: www.haha.org
. . .

# 测试:测试最大连接次数2
[root@nginx ~]# telnet www.haha.org 80
Trying 172.25.254.60...
Connected to www.haha.org.
Escape character is '^]'.
GET / HTTP/1.1             # 输入动作
HOST:www.haha.org		   # 输入访问HOST
						   # 输入回车
						   # 第一连接

HTTP/1.1 200 OK                      
Server: nginx/1.26.2
Date: Mon, 19 Aug 2024 15:03:39 GMT
Content-Type: text/html
Content-Length: 13
Last-Modified: Sun, 18 Aug 2024 14:03:22 GMT
Connection: keep-alive
Keep-Alive: timeout=60 #告知用户最大连接时长为60s,但是真正关闭的时间为前面设定的65s
ETag: "66c1ff2a-d"
Accept-Ranges: bytes

www.haha.org                
GET / HTTP/1.1               # 第二次连接
HOST:www.haha.org

HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Mon, 19 Aug 2024 15:04:39 GMT
Content-Type: text/html
Content-Length: 13
Last-Modified: Sun, 18 Aug 2024 14:03:22 GMT
Connection: close
ETag: "66c1ff2a-d"
Accept-Ranges: bytes

www.haha.org                   
Connection closed by foreign host.  # 按照设定的最大2连接,连接两次之后,连接断开

1.4.9 作为下载服务器的配置

ngx_http_autoindex_module 模块处理以斜杠字符 “/” 结尾的请求,并生成目录列表,可以做为下载服务配置使用

相关指令:

autoindex on | off; 	# 自动文件索引功能,默为off
autoindex_exact_size on | off; #计算文件确切大小(单位bytes),off 显示大概大小(单位K、M),默认on
autoindex_localtime on | off ; #显示本机时间而非GMT(格林威治)时间,默认off
autoindex_format html | xml | json | jsonp; # 显示索引的页面文件风格,默认html
limit_rate rate; 	# 限制响应客户端传输速率(除GET和HEAD以外的所有方法),单位B/s,bytes/second, 
					# 默认值0,表示无限制,此指令由ngx_http_core_module提供
set $limit_rate 4k; # 也可以通变量限速,单位B/s,同时设置,此项优级高.

实现下载站点:

注意:download不需要index.html文件

[root@nginx ~]# mkdir /data/web/download
[root@nginx ~]# dd if=/dev/zero of=/data/web/download/file1 bs=1M count=100

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf 
server {
    listen 80;
    server_name www.haha.org;
    root /data/web/html;
    index index.html;
    error_page 404 /40x.html;
    error_log /var/log/haha.org/error.log;
    access_log /var/log/haha.org/access.log;
    try_files $uri $uri.html $uri/index.html /error/default.html;

    location /pgp {
        root /data/web;
        auth_basic "login password !!!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }

    location = /40x.html{
        root /data/web/errorpage;
    }

    location /download {               # 添加下载服务器模块
        root /data/web;   
        autoindex on;                  # 自动索引功能
        autoindex_exact_size off;	   # 计算文件确切大小(单位bytes)
        autoindex_localtime on;        # on表示显示本机时间而非GMT(格林威治)时间
        limit_rate 1024k;              # 防止带宽过载进行限速,默认不限速
    } 
}

[root@nginx ~]# nginx -s reload

# 测试

测试:

在这里插入图片描述

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值