Nginx模块介绍 核心模块:core module 标准模块:     HTTP modules:         Standard HTTP modules         Optional HTTP modules     Mail modules     Stream modules 第三方模块 使用示例 核心模块 #main block user www www; #进程运行使用的用户和组 pid logs/nginx.pid; #指定存储nginx主进程号的文件路径 include vhost/*.conf; #指明包含进来的其他配置文件 #include mime.type #指明包含进来的其他文件类型 #load module file; #指明要装载的动态模块 worker_processes 4 | auto; #worker进程的数量,应小于等于cpu核心数,auto为当前主 #机cpu核心数 worker_cpu_affinity 0001 0010 0100 1000; #将worker进程与通过cpumask与指定cpu绑定 worker_priority -10; #指定worker进程的nice值,范围[-20,20] worker_rlimite_nofile 2000; #指定worker进程能够打开的最大文件数 #daemon on; #是否已守护进程方式运行Nginx #master_process on; #是否已master-worker模型运行Nginx,默认on error_log /var/log/nginx-error.log info; #错误日志 events { #事件驱动相关配置 use epoll; #指明并发连接请求的处理方式 worker_connections 2048; #每个worker进程能够打开的最大并发连接数 #accpet mutex on | off; #处理新连接的方式,on意味着由每个worker轮流处理新请 #求,off意味着每个新请求到达都会通知所有worker进程 } 标准模块-HTTP modules 与套接字相关配置     1.server { ... }     配置一个虚拟主机     server {         listen address[:PORT] | PORT;         server_name SERVER_NAME;         root  /PATH/TO/DOCUMENT_ROOT;     } 2.listen PORT | address [:PORT] |unix:/PATH/TO/SOCKET_FILE     listen address [:PORT] [ssl] [http2 | spdy] [backlog=number] [rcvbuf=size] [sedbuf=size]     default_server:设置为默认虚拟主机     ssl:设置仅能通过ssl协议提供服务     backlog:设置后援列队长度     rcvbuf:设置接收缓存区大小     sedbuf:设置发送缓存区大小 3.server_name name ... ;     指明虚拟主机的主机名称;后可跟多个由空白字符分割的字符串;         支持*通配符任意长度字符:server_name *.richfit.com www.richfit.*         支持~起始的字符做正则表达模式匹配:server_name ~^www.\d+\.richfit\.com$     匹配机制:         (1)首先是字符串精确匹配         (2)左侧*通配符匹配         (3)右侧*通配符匹配         (4)正则表达式匹配 4.sendfile on | off;     是否开启sendfile功能; 5.tcp_nodelay on | off;     在keepalived模式下的连接是否启用tcp_nodelay选项;表示是否将小文件合并发送     tcp_nopush on | off;     在sendfile模式下是否启用tcp_cork选项;表示是否等待IP首部与文件合并发送 定义路径相关配置 1.root path;     设置web资源路径映射;用于指明用户请求的url所对应的本地文件系统上的文档所在目录路径; 2.location [ = | ~ | ~* | ^~ ] uri { ... }     在一个server中可配置在多个location配置段,用于实现uri到文系统的路径映射;nginx会根据用户请求的URI来检查定义所有的location,并从中选择一个最佳匹配,然后应用配置;     = :对URI做精确匹配     ~ :对URI做正则表达模式匹配,区分大小写     ~*:对URI做正则表达模式匹配,不区分字符大小写     ^~:对URI左侧部分做正则表达模式匹配,不区分大小写     不带符号:匹配起始于该URI的所有URL     匹配优先级:= , ^~ ,~/~* ,不带符号 3.alias path;     定义路径别名,文件映射的另一种机制,仅能用于location配置段 4.index file ...;     请求的默认资源 5.error_page code ... [=[response]] uri;     指定错误代码展示所定义的uri 6.try_files file ... uri;      try_files file ... =code;     通过指定顺序查看文件是否存在并用找到的第一个文件相应请求 定义客户端相关配置 1.keepalived_timeout timeout [header_timeout];     设置保持连接的超时时长,0表示禁止保持连接,默认为75s; 2.keepalived_requests number;     一次长连接允许请求的最大资源数量,默认100 3.keepalived_disable none | browser;     对哪种浏览器禁止长连接 4.send_timeout time;     向客户端发送响应报文的超时时长,此处指两次写操作之间的时间间隔 5.client_body_buffer_size size;     用于接收客户端请求报文body部分的缓冲区大小,默认为16k,超过此大小将被暂存到磁盘上由client_body_tmp_path定义的位置 6.client_body_tmp_path path [ level1 [ level2 [ level3 ];     定义用于存储客户端请求报文body部分的临时存储路径和子目录结构、数量     client_body_tmp_path /var/tmp/client_body 1 2 2     1:表示用1位16进制数字表示一级子目录:0-f     2:表示用2位16进制数字表示二级子目录:00-ff     3:表示用2位16进制数字表示三级子目录:00-ff 对客户端进行限制的相关配置 1.limit_rate rate;     限制响应客户端请求的传输速率,单位bytes/senond,0表示不限制 2.limit_except method { ... };     限制对指定请求方法之外的其他方法使用的客户端 文件操作优化相关配置 1.aio on | off | threads[=pool];     是否开启aio功能 2.directio size | off;     启用Linux的O_DIRECT标记,此处意味着大于等于给定大小时使用, 3.open_file_cache off;     open_file_cache max=N [ inactive=time ];     可缓存最大N个缓存项,Nginx可缓存的信息包括:     (1)文件描述符,最后更新时间,时间戳     (2)打开的目录结构     (3)未找到或没有权限访问的文件相关信息     max=N:表示可缓存项的上限,超过上限后使用LRU算法实现缓存管理;     inactive=time:缓存项的非活动时间,在给定时间内未命中或命中数少于open_file_cache_min_uses定义的次数的缓存项视为非活动项 4.open_file_cache_valid time;     缓存项有效性检查的频率,默认60s 5.open_file_cache_min_uses number;     在open_file_cache中inactive定义的时间内,命中超过多少次可视为活动项 6.open_file_cache_errors on | off;     是否打开缓存项错误日志 ngx_http_access_module模块: 实现基于ip的访问控制 1.allow address | CIDR | unix: | all; 2.deny address | CIDR | unix: | all; ngx_http_auth_basic_module模块: 实现基于用户的访问控制,使用basic机制进行用户认证; 3.auth_basic string | off; 4.auth_basic_user_file file;                                              location /admin/ {                             alias /webapps/app1/data/;                             auth_basic "Admin Area";                             auth_basic_user_file /etc/nginx/.ngxpasswd;                         } ngx_http_stub_status_module模块: 用于输出nginx的基本状态信息;                                          Active connections: 291                      server accepts handled requests                         16630948 16630948 31070465                      Reading: 6 Writing: 179 Waiting: 106                                               Active connections: 活动状态的连接数                     accepts:已接收的客户端请求数量                     handled:已处理的客户端请求数量                     requests:客户端发送的总请求数                     Reading:正在读取客户端请求报文首部的连接数                     Writing:正在向客户端发送响应报文的连接数                     Waiting:正在等待客户端发送请求报文的空闲连接数 5.stub_status;                                          配置示例:                         location  /basic_status {                             stub_status;                         } ngx_http_log_module模块: 1.log_format name string ... ;     定义日志输出格式,string可以nginx核心模块和其他模块内嵌的变量 2.access_log path [ format [ buffer=size ] [ gzip [=level ] ] [ flush=time ] [ if=condition ] ];      access_log off;     访问日志路径配置 3.open_log_file_cache max=N [ inactive=time ] [ min_uses=N] [ valid=time ]     open_log_file_cache off;     缓存日志的元数据相关配置     max:缓存的最大文件描述符数量     inactive:定义非活动时长     min_uses:在inactive时间内超过多少次可以视为活动项     valid:缓存项有效性检查频率 ngx_http_gzip_module模块: 1.gzip on | off;     是否开启响应报文压缩 2.gzip_comp_level level;     压缩等级,level的取值范围为1-9 3.gzip_disable regex ...;     响应报文"User-Agent"中包含匹配regex的报文不启用压缩 4.gzip_min_length length;     启用压缩功能的响应报文阈值 5.gzip_buffers number size;     支持使用压缩功能为其配置的缓存数量和大小 6.gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;     nginx作为代理服务器接收从被代理服务器发送的响应报文在何种情况下启用压缩功能,     off:表示对代理请求不启用压缩     no-cache,no-store,private:表示从被代理服务器接收的报文首部的Cache-Control的值为三者中的一个,则启用压缩功能 7.gzip_types mime-type ...;        只对MIME的文件类型启用压缩功能 #示例 gzip  on; gzip_comp_level 6; gzip_min_length 64; gzip_proxied any; gzip_types text/xml text/css  application/javascript;   ngx_http_ssl_module模块: 1.ssl on | off;    是否对虚拟主机启用https协议 2.ssl_certificate file;     当前虚拟主机使用的pem格式证书文件路径 3.ssl_certificate_key file;     当前虚拟主机使用的证书所对应的私钥文件路径 4.ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];     支持的ssl协议版本,默认支持后三个 5.ssl_session_cache off | none | [builtin[:size]] [shared:name:size];     ssl长连接缓存配置     buildin[ :size ]:使用Openssl内建的缓存,该缓存为此worker独享     shared:name:size:在各worker之间建立一个共享缓存空间 6.ssl_session_timeout time;         客户端连接可复用的ssl session cache中缓存的ssl参数的有效时长 server { listen 443 ssl; server_name www.magedu.com; root /vhosts/ssl/htdocs; ssl on; ssl_certificate /etc/nginx/ssl/nginx.crt; ssl_certificate_key /etc/nginx/ssl/nginx.key; ssl_session_cache shared:sslcache:20m; }             ngx_http_rewrite_module模块: 1.rewrite regex replacement [flag]     将用户请求的URI基于regex所描述的模式进行检查,然后完成替换;     注意:如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个检查;被某条件规则替换完成后,会重新一轮的替换检查,因此,隐含有循环机制;[flag]所表示的标志位用于控制此循环机制;     flag:         last:重写完成后停止对当前URI在当前location中后续的其他重写操作,而后对新URI启动新一轮重写检查;提前重启新一轮循环         break:重写完成后停止对当前URI在当前location中后续的其他重写操作,而后直接跳转到重写配置块之后的其他配置;跳过循环         redirect:重写完成后以临时重定向的方式直接返回重写后的新URI给客户端,由客户端重新发起请求,不能使用http和https开头         permanent:重写完成后以永久重定向的方式直接返回重写后的新URI给客户端,由客户端发重新发起请求 2.return                 return code [text];                 return code URL;                 return URL; 3.rewrite_log on | off;     是否开启重写日志 4.if (condition) { ... }     引入一个新的配置上下文,条件满足时,执行配置块中的配置指令,location,server     condition:                     比较操作符:                         ==                         !=                         ~:模式匹配,区分字符大小写;                         ~*:模式匹配,不区分字符大小写;                         !~:模式不匹配,区分字符大小写;                         !~*:模式不匹配,不区分字符大小写;                     文件及目录存在性判断:                         -e, !-e 判断是否存在                         -f, !-f 判断是否存在文件                         -d, !-d 判断是否存在文件夹                         -x, !-x 判断是否存在且可执行 5.set $variable value;     定义变量并赋值 ngx_http_referer_module模块: 1.valid_referers none | blocked | server_names | string ...; none:请求报文首部没有regerer首部 blocked:请求报文首部的regerer值为空 server_names:参数,其可以有值作为主机名或主机名模式;                         arbitrary_string:直接字符串,但可使用*作通配符;                         regular expression:被指定的正则表达式模式匹配到的字符串;要使用~打头,例如 ~.*\.richfit\.com; valid_referers none block server_names *.richfit.com ~\.richfit\.; if($invalid_referer) { return http://www.magedu.com/invalid.jpg; } ngx_http_proxy_module模块: 1.proxy_pass URL;     proxy_pass后面的路径不带uri时,其会将location的uri传递给后端主机;     proxy_pass后面的路径是一个uri时,其会将location的uri替换为proxy_pass的uri; 2.proxy_set_header field value;     设定发往后端主机的请求报文的值 3.proxy_cache_path     定义可用于proxy功能的缓存     proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time]; 4.proxy_cache zone | off;     指定要缓存的区域或关闭缓存功能 5.proxy_cache_key string;     指定缓存中用于“键”的内容 6.proxy_cache_valid [code ...] time;     对特定响应码的响应内容缓存的时长     定义在http{...}中;                 proxy_cache_path /var/cache/nginx/proxy_cache levels=1:1:1 keys_zone=pxycache:20m max_size=1g;                                  定义在需要调用缓存功能的配置段,例如server{...};                 proxy_cache pxycache;                 proxy_cache_key $request_uri;                 proxy_cache_valid 200 302 301 1h;                 proxy_cache_valid any 1m; 7.proxy_cache_use_stale     proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ... 8.proxy_cache_methods GET | HEAD | POST ...;     请求报文包括列在此处的请求方法是,响应报文使用缓存 9.proxy_hide_header field;     指定nginx将来自被代理服务器响应报文中需要隐藏的报文首部内容 10.proxy_connect_timeout time;     指定nginx与被代理服务器建立连接的超时时间 11.proxy_read_timeout time;      指定读取被代理服务器响应报文的超时时间 12.proxy_send_timeout time;     指定将请求发送给被代理服务器的超时时间 ngx_http_headers_module模块: 1.add_header name value [always];     nginx为发送给客户端的响应报文添加自定义首部或修改首部内容 2.expires [modified] time;     用于定义expire或定义Cache-Control首部的内容 ngx_http_fastcgi_module模块: 1.fastcgi_pass address;     指定fastcgi地址 2.fastcgi_index name;     指定fastcgi默认访问资源 3.fastcgi_param parameter value [if_not_empty];     指定需要传递给fastcgi的参数 4.fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];     定义fastcgi的缓存,缓存位置为磁盘上的文件系统,由path指定的路径来定义, 5.fastcgi_cache zone | off;     调用指定缓存区域来缓存数据 6.fastcgi_cache_key string;     指定用于缓存项的key的字符创 7.fastcgi_cache_methods GET | HEAD | POST ...;     指定哪些方法使用缓存 8.fastcgi_cache_min_uses number;     在inactive时间内命中多少次可被视为活动项 9.fastcgi_cache_valid [code ...] time;     指定不同响应码缓存的时间 10.fastcgi_keep_conn on | off;     指定是否启用fastcgi长连接 ngx_http_upstream_module模块: 1.upstream name { ... }     定义后端服务器组,引入一个新的上下文 2.server address [parameters];             在upstream上下文中server成员,以及相关的参数;Context:    upstream                          address的表示格式:                 unix:/PATH/TO/SOME_SOCK_FILE                 IP[:PORT]                 HOSTNAME[:PORT]                              parameters:                 weight=number                     权重,默认为1;                 max_fails=number                     失败尝试最大次数;超出此处指定的次数时,server将被标记为不可用;                 fail_timeout=time                     设置将服务器标记为不可用状态的超时时长;                 max_conns                     当前的服务器的最大并发连接数;                 backup                     将服务器标记为“备用”,即所有服务器均不可用时此服务器才启用;                 down                     标记为“不可用”; 3.least_conn;     最少连接调度算法,当server权重不同时为wlc 4.ip_hash;     源地址hash调度算法 5.hash key [consistent];     基于指定的key的hash表来实现请求调度 6.keepalive connections;   为每个worker进程保留的空闲连接时长