NGINX03

nginx

ngx_http_access_module

可实现基于ip的访问控制功能

  • allow address |CIDR|unix:|all;
  • deny address |CIDR|unix:|all;

http, server, location, limit_except 自上而下检查,一旦匹配,将生效,条件严格的置前

示例:

1
2
3
4
5
6
7
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}

ngx_http_auth_basic_module

实现基于用户的访问控制,使用basic机制进行用户认证

1、auth_basic string | off;
2、auth_basic_user_file file;

1
2
3
4
location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.ngxpasswd;
}

  • 用户口令文件:

1、明文文本:格式name:password:comment
2、加密文本:由htpasswd命令实现 该命令由httpd-tools rpm包所提供

ngx_http_stub_status_module

用于输出nginx的基本状态信息
Active connections:当前状态,活动状态的连接数
accepts:统计总值,已经接受的客户端请求的总数
handled:统计总值,已经处理完成的客户端请求的总数
requests:统计总值,客户端发来的总的请求数
Reading:当前状态,正在读取客户端请求报文首部的连接的连接数
Writing:当前状态,正在向客户端发送响应报文过程中的连接数
Waiting:当前状态,正在等待客户端发出请求的空闲连接数

示例

1
2
3
4
5
location /status {
stub_status;
allow 172.16.0.0/16;
deny all;
}

ngx_http_log_module

指定日志格式记录请求

  • log_format name string …; string可以使用nginx核心模块及其它模块内嵌的变量
  • access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

示例:

1
2
3
4
log_format  compression '$remote_addr-$remote_user [$time_local] ' 
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" "$gzip_ratio"';
access_log /spool/logs/nginx-access.log ompression buffer=32k;
  • open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];

缓存各日志文件相关的元数据信息
max:缓存的最大文件描述符数量
min_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项
inactive:非活动时长
valid:验证缓存中各缓存项是否为活动项的时间间隔

ngx_http_gzip_module

用gzip方法压缩响应数据,节约带宽

1、gzip on | off;

启用或禁用gzip压缩

2、gzip_comp_level level;

压缩比由低到高:1 到 9 默认:1
3、gzip_disable regex …;

匹配到客户端浏览器不执行压缩

4、gzip_min_length length;

启用压缩功能的响应报文大小阈值

5、gzip_http_version 1.0 | 1.1;

设定启用压缩功能时,协议的最小版本 默认:1.1

6、gzip_buffers number size;

支持实现压缩功能时缓冲区数量及每个缓存区的大小 默认:32 4k 或 16 8k

7、gzip_types mime-type …;

指明仅对哪些类型的资源执行压缩操作;即压缩过滤器
默认包含有text/html,不用显示指定,否则出错

8、gzip_vary on | off;

如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”

9、gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any …;

nginx充当代理服务器时,对于后端服务器的响应报文,在何种条件下启
用压缩功能 off:不启用压缩
expired,no-cache, no-store,private:对后端服务器的响应报文首部
Cache-Control值任何一个,启用压缩功能

示例:

1
2
3
4
5
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 protocol, 建议用listen指令代替

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];

none: 通知客户端支持ssl session cache,但实际不支持
builtin[:size]:使用OpenSSL内建缓存,为每worker进程私有
[shared:name:size]:在各worker之间使用一个共享的缓存

6、ssl_session_timeout time;

客户端连接可以复用ssl session cache中缓存的有效时长,默认5m

示例:

1
2
3
4
5
6
7
8
9
10
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;
ssl_session_timeout 10m;
}

ngx_http_rewrite_module

将用户请求的URI基于PCRE regex所描述的模式进行检查,而后完成重定向替换
例如:http://www.magedu.com –> https://www.magedu.com/

1、rewrite regex replacement [flag]

将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为replacement指定的新的URI
注意:如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个检查;被某条件规则替换完成后,会重新一轮的替换检查
隐含有循环机制,但不超过10次;如果超过,提示500响应码,[flag]所表示的标志位用于控制此循环机制
如果replacement是以http://或https://开头,则替换结果会直接以重向返回给客户端, 即永久重定向301

  • last:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环,不建议在location中使用
  • break:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环,建议在location中使用
  • redirect:临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;使用相对路径,或者http://或https://开头,状态码:302
  • permanent:重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求,状态码:301

2、return

return code [text];
return code URL;
return URL;
停止处理,并返回给客户端指定的响应码,对 301, 302, 303, 307, 308跳转到URL

3、rewrite_log on | off;

是否开启重写日志, 发送至error_log(notice level)

4、set $variable value;

用户自定义变量
注意:变量定义和调用都要以$开头

5、if (condition) { … }

条件满足时,执行配置块中的配置指令;server, location
condition:
比较操作符:

  • = 相同 != 不同
    • ~:模式匹配,区分字符大小写
    • ~*:模式匹配,不区分字符大小写
    • !~:模式不匹配,区分字符大小写
    • !~*:模式不匹配,不区分字符大小写

文件及目录存在性判断:

  • -e, !-e 存在(包括文件,目录,软链接)
  • -f, !-f 文件 -d, !-d 目录 -x, !-x 执行

ngx_http_referer_module

用来阻止Referer首部无有效值的请求访问,可防止盗链

1、valid_referers none|blocked|server_names|string …;

定义referer首部的合法可用值,不能匹配的将是非法值
none:请求报文首部没有referer首部
blocked:请求报文有referer首部,但无有效值
server_names:参数,其可以有值作为主机名或主机名模式
arbitrary_string:任意字符串,但可使用*作通配符
regular expression:被指定的正则表达式模式匹配到的字符串,要使用~开头,
例如: ~.*.magedu.com

示例:

1
2
3
4
5
valid_referers none block server_names *.magedu.com *.mageedu.com 
magedu.* mageedu.* ~\.magedu\.;
if ($invalid_referer) {
return 403 http://www.magedu.com;
}

ngx_http_proxy_module

转发请求至另一台主机

1、proxy_pass URL;

Context:location, if in location, limit_except

注意:proxy_pass后面路径不带uri时,会将location的uri传递(附加)给后端主机

1
2
3
4
5
6
7
8
server {
...
server_name HOSTNAME;
location /uri/ {
proxy_pass http://host[:port]; 最后没有/
}
...
}

上面示例:http://HOSTNAME/uri –> http://host/uri
如果上面示例中有 /,即:http://host[:port]/
意味着:http://HOSTNAME/uri –> http://host/ 即置换

  • proxy_pass后面的路径是一个uri时,其会将location的uri替换为proxy_pass的uri
1
2
3
4
5
6
7
8
server {
...
server_name HOSTNAME;
location /uri/ {
proxy_pass http://host/new_uri/;
}
...
}

http://HOSTNAME/uri/ –> http://host/new_uri/

  • 如果location定义其uri时使用了正则表达式的模式,则proxy_pass之后必须不能使用uri;用户请求时传递的uri将直接附加至后端服务器之后
1
2
3
4
5
6
7
8
server {
...
server_name HOSTNAME;
location ~|~* /uri/ {
proxy_pass http://host; 不能加/
}
...
}

http://HOSTNAME/uri/ –> http://host/uri/

2、proxy_set_header field value;

设定发往后端主机的请求报文的请求首部的值

Context: http, server, location

1
2
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

请求报文的标准格式如下:
X-Forwarded-For: client1, proxy1, proxy2

3、proxy_cache_path;

定义可用于proxy功能的缓存;Context:http

1
2
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; 默认off

指明调用的缓存,或关闭缓存机制;Context:http, server, location

5、proxy_cache_key string;缓存中用于“键”的内容

默认值:proxy_cache_key $scheme$proxy_host$request_uri;

6、proxy_cache_valid [code …] time;

定义对特定响应码的响应内容的缓存时长,定义在http{…}中

示例:

1
2
3
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
ngx_http_proxy_module

示例:在http配置定义缓存信息

1
2
3
proxy_cache_path /var/cache/nginx/proxy_cache
levels=1:1:1 keys_zone=proxycache:20m
inactive=120s max_size=1g;

说明:proxycache:20m 指内存中缓存的大小,主要用于存放key和metadata(如:使用次数)
max_size=1g 指磁盘存入文件内容的缓存空间最大值
调用缓存功能,需要定义在相应的配置段,如server{…};

1
2
3
4
proxy_cache proxycache;
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 …;

对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存

9、proxy_hide_header field;

默认nginx在响应报文中不传递后端服务器的首部字段Date, Server, X-Pad, X-Accel-等,用于隐藏后端服务器特定的响应首部

10、proxy_connect_timeout time;

定义与后端服务器建立连接的超时时长,如超时会出现502错误,默认为60s,一般不建议超出75s

11、proxy_send_timeout time;

将请求发送给后端服务器的超时时长;默认为60s

12、proxy_read_timeout time;

等待后端服务器发送响应报文的超时时长,默认为60s

ngx_http_headers_module模块

向由代理服务器响应给客户端的响应报文添加自定义首部,或修改指定首部的值

1、add_header name value [always];

添加自定义首部

1
2
3
add_header X-Via $server_addr;
add_header X-Cache $upstream_cache_status;
add_header X-Accel $server_name;

2、add_trailer name value [always];

添加自定义响应信息的尾部

ngx_http_fastcgi_module

转发请求到FastCGI服务器,不支持php模块方式

1、fastcgi_pass address;address为后端的fastcgi server的地址可用位置:location, if in location
2、fastcgi_index name;fastcgi默认的主页资源示例:fastcgi_index index.php;
3、fastcgi_param parameter value [if_not_empty];设置传递给 FastCGI服务器的参数值,可以是文本,变量或组合

示例1:
1)在后端服务器先配置fpm server和mariadb-serve
2)在前端nginx服务上做以下配置:

1
2
3
4
5
6
7
location ~* \.php$ {
fastcgi_pass 后端fpm服务器IP:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /app/php$fastcgi_script_name;
include fastcgi_params;

}

示例2:通过pm_status和ping来获取fpm server状态信息

1
2
3
4
5
location ~* ^/(pm_status|ping)$ {
include fastcgi_params;
fastcgi_pass 后端fpm服务器IP:9000;
fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
}

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 缓存位置为磁盘上的文件系统
  • max_size=size 磁盘path路径中用于缓存数据的缓存空间上限
  • levels=levels:缓存目录的层级数量,以及每一级的目录数量
  • levels=ONE:TWO:THREE 示例:leves=1:2:2
  • keys_zone=name:size k/v映射的内存空间的名称及大小
  • inactive=time 非活动时长

5、fastcgi_cache zone | off;

调用指定的缓存空间来缓存数据 可用位置:http, server, location

6、fastcgi_cache_key string;

定义用作缓存项的key的字符串
示例:fastcgi_cache_key $request_rui;

7、fastcgi_cache_methods GET | HEAD | POST …;

为哪些请求方法使用缓存

8、fastcgi_cache_min_uses number;

缓存空间中的缓存项在inactive定义的非活动时间内至少要被访问到此处所指定的次数方,可被认作活动项

9、fastcgi_keep_conn on | off;

收到后端服务器响应后,fastcgi服务器是否关闭连接,建议启用长连接

10、fastcgi_cache_valid [code …] time;

不同的响应码各自的缓存时长

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
http {
fastcgi_cache_path /var/cache/nginx/fcgi_cache levels=1:2:1 keys_zone=fcgicache:20m inactive=120s;
...
server {
location ~* \.php$ {
...
fastcgi_cache fcgicache;
fastcgi_cache_key $request_uri;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 301 1h;
fastcgi_cache_valid any 1m;
...
}
}
}

ngx_http_upstream_module

用于将多个服务器定义成服务器组,而由proxy_pass, fastcgi_pass等指令进行引用

1、upstream name { … }

定义后端服务器组,会引入一个新的上下文,默认调度算法是wrr Context: http

1
2
3
4
5
upstream httpdsrvs {
server ...
server...
...
}

2、server address [parameters];

在upstream上下文中server成员,以及相关的参数;Context:upstream

  • address的表示格式:
    • unix:/PATH/TO/SOME_SOCK_FILE
    • IP[:PORT]
    • HOSTNAME[:PORT]
  • parameters:
    • weight=number 权重,默认为1
    • max_conns 连接后端报务器最大并发活动连接数,1.11.5后支持
    • max_fails=number 失败尝试最大次数;超出此处指定的次数时,server将被标记为不可用,默认为1
    • fail_timeout=time 后端服务器标记为不可用状态的连接超时时长,默认10s
    • backup 将服务器标记为“备用”,即所有服务器均不可用时才启用
    • down 标记为“不可用”,配合ip_hash使用,实现灰度发布

3、ip_hash 源地址hash调度方法

4、least_conn 最少连接调度算法

当server拥有不同的权重时其为wlc,
当所有后端主机连接数相同时,则使用wrr,适用于长连接

5、hash key [consistent] 基于指定的key的hash表来实现对请求的调度,此处的key可以直接文本、变量或二者组合

作用:将请求分类,同一类请求将发往同一个upstream server,使用consistent参数,将使用ketama一致性hash算法,适用于后端是Cache服务器(如varnish)时使用

1
2
hash $request_uri consistent;
hash $remote_addr;

6、keepalive 连接数N;

为每个worker进程保留的空闲的长连接数量,可节约nginx端口,并减少连接管理的消耗

7、ngx_stream_core_module模块

模拟反代基于tcp或udp的服务连接,即工作于传输层的反代或调度器

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
stream {
upstream mysqlsrvs {
server 192.168.0.10:3306;
server 192.168.0.11:3306;
hash $remote_addr consistent;
}
server {
listen 172.16.100.100:3306;
proxy_pass mysqlsrvs;
proxy_timeout 60s;
proxy_connect_timeout 10s;
}
}

-------------本文结束感谢您的阅读-------------