深入解析Nginx核心模块

内容分享4天前发布
0 0 0

在本篇博客文章中,我们将深入探讨Nginx的核心模块。了解这些核心模块的功能和使用方法,可以帮助我们更好地配置和优化Nginx服务器,以满足各种不同的网络服务需求。

Nginx核心模块概览
Nginx是一款高性能的HTTP和反向代理服务器,其灵活性和高效性很大程度上得益于丰富的模块系统。Nginx的模块可以分为三类:核心模块、处理程序模块和过滤器模块。本文将重点介绍一些关键的核心模块。

Nginx核心模块

nginx官网帮助文档
http://nginx.org/en/docs/
tengine 帮助文档
https://tengine.taobao.org/documentation_cn.html
Nginx的配置文件的组成部分
主配置文件:nginx.conf
子配置文件: include conf.d/*.conf
fastcgi,uwsgi,scgi 等协议相关的配置文件
mime.types:支持的mime类型,MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型,MIME消息能包含文本、图像、音频、视频以及其他应用程序专用的数据,是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式
MIME参考文档
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Guides/MIME_types
nginx 配置文件格式说明


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

bash
12345678

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


directive value [value2 ...];

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

bash
12345678

主配置文件结构:四部分


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

#事件驱动相关的配置
event {
 ...
 }
 
#http/https 协议相关配置段
http {
 ...
 } 

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

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

bash

深入解析Nginx核心模块12345678910111213141516171819202122

默认的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 (快速拷贝到kernelsocket buffer) >>协议栈。
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
}

bash

深入解析Nginx核心模块1234567891011121314151617181920212223242526272829303132333435

全局配置

Main 全局配置段常见的配置指令分类
正常运行必备的配置
优化性能相关的配置
用于调试及定位问题相关的配置
事件驱动相关的配置


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服务器的性能。
CPU MASK: 00000001:0号CPU
          00000010:1号CPU
          10000000:7号CPU
#示例:
worker_cpu_affinity 0001 0010 0100 1000;第0号---第3号CPU
worker_cpu_affinity 0101 1010;

#示例
worker_processes  4;
worker_cpu_affinity 00000010 00001000 00100000 10000000;
[root@ubuntu2404 ~]#ps axo pid,cmd,psr | grep nginx
45768 nginx: master process /apps   0
45769 nginx: worker process         0
45770 nginx: worker process         1
45870 grep --color=auto nginx       0

#auto 绑定CPU
#The special value auto (1.9.10) allows binding worker processes automatically to available CPUs:
worker_processes auto; 
worker_cpu_affinity auto;
#The optional mask parameter can be used to limit the CPUs available for automatic binding:
worker_cpu_affinity auto 01010101;

#错误日志记录配置,语法:error_log file  [debug | info | notice | warn | error | crit | alert | emerg]
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
error_log  /apps/nginx/logs/error.log error; 

#pid文件保存路径
pid        /apps/nginx/logs/nginx.pid;

worker_priority 0; #工作进程优先级,-20~20(19)
worker_rlimit_nofile 65536; #所有worker进程能打开的文件数量上限,包括:Nginx的所有连接(例如与代理服务器的连接等),而不仅仅是与客户端的连接,另一个考虑因素是实际的并发连接数不能超过系统级别的最大打开文件数的限制,最好与ulimit -n 或者limits.conf的值保持一致,默认不限制

daemon off;  #前台运行Nginx服务用于测试、或者以容器运行时,需要设为off
master_process off|on; #是否开启Nginx的master-worker工作模式,仅用于开发调试场景,默认为on

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

bash

深入解析Nginx核心模块12345678910111213141516171819202122232425262728293031323334353637383940414243444546

实现nginnx高并发配置


[root@centos7 ~]#ulimit  -n 102400
[root@centos7 ~]#while true;do  ab -c 5000 -n 10000 http://192.168.1.20/;sleep 0.5;done

#Ubuntu内核参数默认值比较高,无需调整
[root@ubuntu2404 ~]#pidof nginx
45770 45769 45768
[root@ubuntu2404 nginx]#cat /proc/45768/limits 
Limit                     Soft Limit           Hard Limit           Units
Max open files            100000               100000               files     

#如果systemd启动,则需要修改nginx.service文件中加LimitNOFILE=100000,才能有效
[root@ubuntu2404 ~]#vim /lib/systemd/system/nginx.service
[Service]
......
LimitNOFILE=10000
.....

#如果非systemd启动,可以修改下面pam限制
[root@ubuntu2404 ~]#vim /etc/security/limits.conf 
*                soft    nofile          1000000
*                hard    nofile          1000000
[root@rocky9 ~]# vim /apps/nginx/conf/nginx.conf
worker_cpu_affinity auto;
events {
    worker_connections  10240;
    use epoll;
}
[root@ubuntu2404 ~]# systemctl restart nginx
[root@ubuntu2404 ~]# watch -n1 'ps axo pid,cmd,psr | grep nginx'  验证进程优先级

bash

深入解析Nginx核心模块1234567891011121314151617181920212223242526272829

http 配置块

http 协议相关的配置结构


http {
   ...
   ...  #各server的公共配置
   server {    
        #每个server用于定义一个虚拟主机,第一个server为默认虚拟服务器
   ...
}
   server {     
     ...
     server_name   #虚拟主机名
     root          #主目录
     alias         #路径别名
     location [OPERATOR] URL {     #指定URL的特性
            ...
           if CONDITION {
               ...
      }
     }
   }		
 }

bash

深入解析Nginx核心模块1234567891011121314151617181920

http协议配置说明


http {
    include       mime.types; #导入支持的文件类型,是相对于/apps/nginx/conf的目录
    default_type  application/octet-stream; #除mime.types中文件类型外,设置其它文件默认类型,访问其它类型时会提示下载不匹配的类型文件

#日志配置部分
#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  logs/access.log  main;

#自定义优化参数
    sendfile        on; 
    #tcp_nopush     on;  开启sendfile的情况下,合并请求后统一发送给客户端,必须开启sendfile
    #tcp_nodelay    off; 开启keepalived模式下的连接是否启用TCP_NODELAY选项,为off时,延迟0.2s发送,默认On时,不延迟发送,立即发送用户响应报文。
    #keepalive_timeout  0;
    keepalive_timeout  65 65; #设置会话保持时间,第二个值为响应首部:keep-Alived:timeout=65,可以和第一个值不同
    #gzip  on; #开启文件压缩
server {
        listen       80 default_server; #设置监听地址和端口,多个虚拟机时当前是否是默认的虚拟主机,default_server表示是默认主机,否则排在前面server为默认主机
        server_name  localhost; #设置server name,可以以空格隔开写多个并支持正则表达式,如:*.wang.com  www.wang.*  ~^wwwd+.wang.com$  
        #charset koi8-r; #设置编码格式,默认是俄语格式,建议改为utf-8
        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;  #定义错误页面
        location = /50x.html {
            root   html;
        }
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {  以http的方式转发php请求到指定web服务器
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ .php$ {    #以fastcgi的方式转发php请求到php处理
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {   拒绝web形式访问指定文件,如很多的网站都是通过.htaccess文件来改变自己的重定向等功能。
        #    deny  all;
        #}
    }
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {   #自定义虚拟server
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm; #指定默认网页文件,此指令由ngx_http_index_module模块提供
    #    }
    #}
    # HTTPS server
    #
    #server {  #https服务器配置
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}

bash

深入解析Nginx核心模块1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889

MIME


#在响应报文中将指定的文件扩展名映射至MIME对应的类型
include           /etc/nginx/mime.types;
default_type      application/octet-stream;#除mime.types中的类型外,指定其它文件的默认MIME类型,浏览器一般会提示下载
types {
    text/html  html;
    image/gif  gif;
    image/jpeg jpg;
 }
#MIME参考文档:
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_Types

bash

深入解析Nginx核心模块12345678910

识别php文件为text/html


[root@rocky9 html]# vim /app/nginx/html/test.php 
<?php
phpinfo();
?>
[root@centos7 ~]# curl www.caoge.com/test.php -I
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Thu, 28 Nov 2024 05:12:07 GMT
Content-Type: application/octet-stream
Content-Length: 21
Last-Modified: Thu, 28 Nov 2024 05:10:13 GMT
Connection: keep-alive
ETag: "6747fb35-15"
Accept-Ranges: bytes

[root@rocky9 nginx]# vim conf/nginx.conf
.....
http {
    include       mime.types;
    default_type  text/html;
.....
或者修改为下面这一行
http {
    include       mime.types;
    default_type  application/octet-stream;
    types{
        text/plain  php;  #加此行
    }

[root@rocky9 nginx]# nginx -s reload
[root@centos7 ~]# curl www.caoge.com/test.php -I
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Thu, 28 Nov 2024 05:13:52 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 21
Last-Modified: Thu, 28 Nov 2024 05:10:13 GMT
Connection: keep-alive
ETag: "6747fb35-15"
Accept-Ranges: bytes

bash

深入解析Nginx核心模块12345678910111213141516171819202122232425262728293031323334353637383940

指定响应报文server首部


#是否在响应报文的Server首部显示nginx版本,默认是on
server_tokens on | off | build | string;

bash
12

修改server字段


如果想自定义响应报文的nginx版本信息,需要修改源码文件,重新编译
如果server_tokens on,修改 src/core/nginx.h  修改第13-14行,如下示例
#define NGINX_VERSION      "1.68.9"
#define NGINX_VER          "caoge/" NGINX_VERSION
如果server_tokens off,修改 src/http/ngx_http_header_filter_module.c 
第49行,如下示例:
static char ngx_http_server_string[] = "Server: nginx" CRLF;
把其中的nginx改为自己想要的文字即可,如:caoge

bash
12345678

修改server头部信息


[root@rocky9 nginx]# vim conf/nginx.conf
......
server_tokens off;
......
[root@centos7 ~]# curl www.caoge.com -I
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 28 Nov 2024 14:26:32 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 615
Last-Modified: Sun, 24 Nov 2024 12:16:29 GMT
Connection: keep-alive
ETag: "6743191d-267"
Accept-Ranges: bytes

bash

深入解析Nginx核心模块1234567891011121314

指定字符集

指定字符集utf-8,防止网页显示乱码


#是否在响应报文中的Content-Type显示指定的字符集,默认off不显示
charset | off;

#示例
charset utf-8;

bash
12345

常见核心模块配置

基于不同的IP、不同的端口以及不用得域名实现不同的虚拟主机,依赖于核心模块ngx_http_core_module实现
新建一个 PC web 站点


[root@rocky9 nginx]# vim conf/nginx.conf
http{
  ......
  include   /app/*.conf;  #在配置文件的最后面添加此行,注意不要放在最前面,会导致前面的命令无法生效
  ......
}
#创建PC网站配置
[root@rocky9 app]# cat pc.conf 
server {
  	server_name m.caoge.com;
  	root /data/nginx/ ;
}
[root@rocky9 ~]# mkdir /data/nginx
[root@rocky9 ~]# echo "pc web "> /data/nginx/index.html
[root@rocky9 ~]# nginx -s reload

[root@centos7 ~]# curl m.caoge.com
pc web 

bash

深入解析Nginx核心模块123456789101112131415161718

新建一个 Mobile web 站点


[root@rocky9 app]# vim mobile.conf 
server {
      server_name caoge.cn;
      root /data/nginx/moblie ;
}
[root@rocky9 ~]# mkdir /data/nginx/moblie
[root@rocky9 ~]# echo "moblie web " >/data/nginx/moblie/index.html
[root@rocky9 ~]# nginx -sreload

[root@centos7 ~]# curl caoge.cn/m.html
moblie web 

bash

深入解析Nginx核心模块1234567891011

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


[root@rocky9 app]# vim pc.conf 
server {
        server_name m.caoge.com;
        root /data/nginx/ ;
        location  /pc {
        root   /data/nginx;  #必须要在nginx目录中创建一个名为pc的目录才可以访问,否则报错。
}

}
[root@rocky9 ~]# mkdir /data/nginx/pc
[root@rocky9 ~]# echo "pc目录下" >/data/nginx/pc/m.html
[root@rocky9 app]# nginx -s reload

[root@centos7 ~]# curl m.caoge.com/pc/m.html
pc目录下

bash

深入解析Nginx核心模块123456789101112131415

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


server {
  listen 80;
  server_name www.wang.org;
  location / {
    root /data/nginx/html/pc;
  }
  location /about { #注意about后不要加/ , 使用alias的时候uri后面如果加了斜杠,则下面的路径配置必须加斜杠,否则403
    alias /opt/html; #当访问about的时候,会显示alias定义的/opt/html里面的内容
  }
 }
#重启Nginx并访问测试

bash

深入解析Nginx核心模块1234567891011

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


root 给定的路径对应于location中的/uri 左侧的/
alias 给定的路径对应于location中的/uri 的完整路径 

bash
12

location 的详细使用

在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,按一定的优先级找出一个最佳匹配,而后应用其配置在没有使用正则表达式的时候,nginx会先在server中的多个location选取匹配度最高的一个uri,uri是用户请求的字符串,即域名后面的web文件路径,然后使用该location模块中的正则url和字符串,如果匹配成功就结束搜索,并使用此location处理此请求
location 官方帮助


http://nginx.org/en/docs/http/ngx_http_core_module.html#location

bash
1

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

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

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

bash

深入解析Nginx核心模块123456789101112

官方示例


location = / {
    [ configuration A ]
 }
 location / {
    [ configuration B ]
 }
 location /documents/ {
    [ configuration C ]
 }
 location ^~ /images/ {
    [ configuration D ]
 }
 location ~* .(gif|jpg|jpeg)$ {
    [ configuration E ]
 }

The “/” request will match configuration A(?), the “/index.html” request will 
match configuration B,the “/documents/document.html” request will match configuration C, the 
“/images/1.gif” request will match configuration D, and the “/documents/1.jpg” request will match configuration E.

bash

深入解析Nginx核心模块12345678910111213141516171819

示例


[root@rocky9 app]# vim pc.conf 
server {
 listen 80;
 server_name m.caoge.com;
 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)';
}
}
[root@rocky9 app]# nginx -s reload

[root@centos7 ~]# curl m.caoge.com/
location = /
[root@centos7 ~]# curl m.caoge.com/documents
location /
[root@centos7 ~]# curl m.caoge.com/documents/
location /documents/
[root@centos7 ~]# curl m.caoge.com//images/
location ^~ /images/
[root@centos7 ~]# curl m.caoge.com/a.jpg
location ~* .(gif|jpg|jpeg)

bash

深入解析Nginx核心模块12345678910111213141516171819202122232425262728293031323334353637

匹配案例-精确匹配
在server部分使用location配置一个web界面,例如:当访问nginx 服务器的/logo.jpg的时候要显示指定 html文件的内容精确匹配一般用于匹配组织的logo等相对固定的URL,匹配优先级最高
精确匹配logo


[root@rocky9 app]# vim pc.conf 
server {
         listen 80;
        server_name m.caoge.com;        
        location / {
        root /data/nginx;
        }
        location = /log.jpg {
        root /data/nginx/pc;
}

}
[root@rocky9 app]# nginx -s reload

[root@centos7 ~]# curl m.caoge.com/pc/log.jpg

bash

深入解析Nginx核心模块123456789101112131415

匹配案例-区分大小写
~实现区分大小写的模糊匹配,以下范例中, 如果访问uri中包含大写字母的JPG,则以下location匹配 Ax.jpg条件不成功,因为 ~ 区分大小写,当用户的请求被执行匹配时发现location中定义的是小写的 jpg,本次访问的uri匹配失败,后续要么继续往下匹配其他的location(如果有),要么报错给客户端


location ~ /A.?.jpg { #匹配字母A开头的jpg图片,后面?表示A后面零次或一个字符
    index index.html;
    root /data/nginx/html/image;
 }
#重启Nginx并访问测试
#将只能访问以小写字符的jpg图片,不能识别大写的JPG结尾的图片

bash
123456

匹配案例-不区分大小写
~* 用来对用户请求的uri做模糊匹配,uri中无论都是大写、都是小写或者大小写混合,此模式也都会匹配,通常使用此模式匹配用户request中的静态资源并继续做下一步操作,此方式使用较多
注意: 此方式中,对于Linux文件系统上的文件仍然是区分大小写的,如果磁盘文件不存在,仍会提示404


#正则表达式匹配:
  location ~* /A.?.jpg {
    index index.html;
    root /opt/nginx/html/image;
  }
#重启Nginx并访问测试
对于不区分大小写的location,则可以访问任意大小写结尾的图片文件,如区分大小写则只能访问Aa.jpg此
类文件,不区分大小写则可以访问除了aa.jpg以外,还有其它的资源比如Aa.JPG、aA.jPG这样的混合名称文
件,但是还同时也要求nginx服务器的资源目录有相应的文件,比如:必须有Aa.JPG,aA.jPG这样文件存在。

bash
123456789

匹配案例-URI开始


location ^~ /images {
    root /data/nginx/;
    index index.html;
}
location  /api {
    alias /data/nginx/api;
    index index.html;
 }
#重启Nginx并访问测试,实现效果是访问/images和/app返回不同的结果
[root@centos8 ~]# curl  http://www.caoge.com/images/
images
[root@centos8 ~]# curl  http://www.caoge.com/api/
api web

bash

深入解析Nginx核心模块12345678910111213

匹配案例-文件名后缀


[root@centos8 ~]# mkdir /data/nginx/static
#上传一个图片到/data/nginx/static
location ~* .(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js|css)$ {
    root /data/nginx/static;
    index index.html;
}
#重启Nginx并访问测试 

bash
1234567

生产使用案例


#直接匹配网站根会加速Nginx访问处理
location = /index.html {
   ......;
}
location / {
   ......;
}
#静态资源配置方法1
 location ^~ /static/ {
    ......;
}
#静态资源配置方法2,应用较多
location ~* .(gif|jpg|jpeg|png|css|js|ico)$ {
   ......;
}
#多应用配置
location ~* /app1  {
     ......;
}
location ~* /app2  {
     ......;
}

bash

深入解析Nginx核心模块12345678910111213141516171819202122

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


cat /etc/nginx/conf.d/www.caoge.com.conf
server {
 listen 80;
 server_name www.caoge.com;
 root /data/www;
 location / {
 index index.html;
  }
#如果出现异常,则重新定向到@error_404这个location上
error_page 404 @error_404;
 location @error_404 {
 default_type text/html;
 charset utf8;
 return 200 '你访问的页面可能走丢了!';
   }
}

bash

深入解析Nginx核心模块12345678910111213141516

结语
理解Nginx的核心模块及其功能,是掌握Nginx配置的基础。每个模块都有其独特的用途,合理地组合使用它们,可以让你的Nginx服务器更加安全、高效和灵活。希望这篇文章能帮助你更深入地了解Nginx,并为你的Web服务器管理之旅提供有力的支持。

请随时关注我们的博客,获取更多关于Nginx和其他技术主题的深度解析!

© 版权声明

相关文章

暂无评论

none
暂无评论...