Nginx作为web服务器
Nginx配置
main配置段常见的配置指令
正常运行必备的配置
user
Syntax: user user [group];
Default: user nobody nobody
Context: main
定义Nginx的worker进程的属主和属组pid /path/to/pid_file;
指定存储NGINX主进程进程号的文件路径include file | mask;
指明包含进来的其他配置文件片段load_module file;
指明要装载的动态模块性能优化相关的配置
worker_processes number | auto;
worker进程的数量,通常应该等于小于当前主机的cpu的物理核心数
auto:当前主机物理CPU核心数worker_cpu_affinity cpumask…;
worker_cpu_affinity auto [cpumask];
nginx进程的CPU亲缘性,让特定进程与特定CPU绑定,提升缓存的命中率,提升性能。
CPU mask:bit mask
00000000:
0000 0001:0号CPU
0000 0010:1号CPU
0000 0100:2号CPU
… …0000 0011:0和1号CPU;
worker_priority number;
指定worker进程的nice值,设定worker进程优先级;[-20,20]worker_rlimit_nofile number;
worker进程所能够打开的文件数连接上限调试、定位问题
daemon on|off
是否以master/worker模型运行NGINX;默认为onerror_log file [level];
时间驱动相关的配置
events {
…
}
worker_connections number;
每个worker进程所能够打开的最大并发连接数数量
worker_processes * worker_connections为网站最大并发连接量use method;
执行并发连接请求的处理方法
use epoll;accept_mutex on | off;
处理新的连接请求的方法,on意味着由各worker轮流处理新情求,off意味着每个新情求的到达都会通知所有的worker进程。
与套接字相关的配置
配置在http{}语句块内
server {…}
配置一个虚拟主机server{
listen address[:port] | PORT;
server_name SERVER_NAME;
root /path/to/document_root;
}listen PORT|address[:port]|unix:/path/to/socket_file
listen address[:port] [default_server] [ssl] [http2|spdy] [backlog=number] [rcvbuf=size] [sndbuf=size]default_server:设定为默认虚拟主机;
ssl:限制仅能够通过ssl连接提供服务;
backlog=number:后援队列长度;
rcvbuf=size:接受缓冲区大小;
sndbuf=size:发送缓冲区大小;server_name name …;
指明虚拟主机的主机名称;后可跟多个由空白字符分割的字符串;
支持*通配任意长度的任意字符串;servername *.msq.com www.msq.\*
支持~起始的字符做正则表达式模式匹配;server_name ~^www\d+.msq.com$匹配机制:
首先是字符串精确匹配
左侧*通配符
右侧*通配符
正则表达式tcp_nodelay on|off;
在keepalived模式下的连接是否启用TCP_NODELAY选项;建议启用
tcp_nopush on|off;
在sendfile模式下,是否启用TCP_CORK选项;sendfile on|off;
是否启用sendfile功能;内核直接将封装的效应报文返回给客户端。
定义路径相关的配置
root path;
设置web资源路径映射,用于指明用户请求的URL所对应的本地文件系统上的文档所在目录路径;可用的位置:http,server,location,if in location;location [=|
|*|^~] uri {…}
在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;nginx会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配,而后应用其配置。=:对URI做正则表达式模式匹配,区分字符大小写;
:对URI做正则表达式模式匹配,区分字符大小写;:对URI的左半部分做匹配检查,不区分字符大小写;
~*:对URI做正则表达式模式匹配,不区分字符大小写;
^
不带符号:以URI为前缀的所有URI;
匹配优先级:=, ^, ~/*,不带符号;
location配置示例:
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.
alias path;
定义别名,文档映射的另一种机制;仅能用于location上下文;
注意:location中使用root指令和alias指令的意义不同;root:给定的路径对应于location中的/uri/左侧的/;
alias:给定的路径对应于location中的/uri/右侧的/;index file …;
默认资源,可放在http,server,location字段。error_page code … [=[response]] uri;
defined the URI that will be shown for the specified errors.error_page 404 /404.html;
location = /404.html {
root “/www/error_pages”;
}try_file file … rui;
定义客户端请求的相关配置keepalive_timeout timeout [header_timeout];
设定保持连接的超时时长,0表示禁止长连接;默认为75s。keepalive_requests number;
在一次长连接上所允许请求的资源的最大数量,默认为100;keepalived_disable none | browser …;
对那种浏览器禁用长连接。send_timeout time;
向客户端发送响应报文的超时时长,此处,是指两次写操作之间的间隔时长。client_body_buffer_size size;
用于接受客户端请求报文的body部分的缓冲区大小;默认为16k;超出此大小时,其将被暂存到磁盘上的有client_body_temp_path指令所定义的位置;client_body_temp_path path [level1 [level2 [level3]]];
设定用于存储客户端请求报文的body部分的临时存储路径及子目录结构和数量;
对客户端进行限制的相关配置
limit_rate rate;
限制响应给客户端的传输速率,单位是bytes/second,0表示无限制;limit_except method … {…}
限制对指定的请求方法之外的其他方法的使用客户端limit_except GET {
allow 192.168.1.0/24;
deny all;
}
文件操作优化的配置
aio on|off|threads[=pool];
是否启用aio功能,异步io功能,开启会大幅提升nginx性能。directio size | off;
在linux主机启用O_DIRECT标记,此处意味着文件大于等于给定的大小时使用,例如directio 4m;open_file_cache off;
open_file_cache max=N [incative=time];max=N:可缓存的缓存项上限;达到上线后会使用LRU算法实现缓存管理;
inactive=time:缓存项的非活动时长,在此处指定的市场内未被命中的或命中的次数少于open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项。
nginx可以缓存以下三种信息:
文件的描述符、文件大小和最近一次的修改时间;
打开的目录结构
没有找到的或者没有权限访问的文件的相关信息;
open_file_cache_min_uses number;
在open_file_cache指令的inactive参数指定的时长内,至少应该被命中多少次方可被归类为活动项;open_file_cache_errors on | off;
是否缓存查找时发生错误的文件一类的信息;
Nginx模块
ngx_http_access_module模块
实现基于ip的访问控制功能
可应用于http,server,location,limit_except语句块
allow address | CIDR | unix: | all;
deny address | CIDR | unix: |all;
ngx_http_auth_basic_module模块
实现基于用户的访问控制权限,使用basic机制进行用户认证。
- auth_basic string | off;
- auth_basic_user_file file;
location /admin/ {
alias /webapps/app1/data/;
auth_basic “Admin Area”;
auth_basic_user_file /etc/nginx/.ngxpasswd;
}
注意:htpasswd命令由httpd-tools包提供。
示例:
1 | [root@host-10-10-10-4 ~]#vi /etc/nginx/nginx.conf |
此时就需要在客户端先登录才能查看网站内容。
ngx_http_stub_status_module模块
用于输出nginx的基本状态信息;
使用示例:
1 | [root@host-10-10-10-4 ~]#vi /etc/nginx/nginx.conf |
输出信息详解:
Active connections: 活动状态的连接数;
accepts:已经接受的客户端请求的总数;
handled:已经处理完成的客户端请求的总数;
requests:客户端发来的总的请求数;
Reading:处于读取客户端请求报文首部的连接的连接数;
Writing:处于向客户端发送响应报文过程中的连接数;
Waiting:处于等待客户端发出请求的空闲连接数;
ngx_http_log_module模块
控制用户请求的记录格式
log_format name string …;
string可以使用nginx核心模块及其他模块内嵌的变量;
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]]; access_log off; #访问日志文件路径,格式及相关的缓冲配置;
buffer=size
flush=time
示例:
1 | log_format main '$remote_addr(远程地址) - $remote_user(远程用户) [$time_local](访问时间) "$request"(请求方式) ' |
open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;
缓存各日志文件相关的元数据信息;
max:缓存的最大文件描述符数量;
min_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项;
inactive:非活动时长;
valid:验正缓存中各缓存项是否为活动项的时间间隔;
ngx_http_gzip_module模块
gzip on | off;
是否启用压缩功能gzip_comp_level level;
设置压缩级别;gzip_disable regex …;
对匹配到的客户端浏览器不启用压缩功能;gzip_min_length length;
启用压缩功能的响应报文大小阈值;大于该值的响应报文才进行压缩;gzip_buffers number size;
支持实现压缩功能时为其配置的缓冲区数量及每个缓冲区的大小;gzip_proxied off | expired | no-cache | bo-store | private | no_last_modified | no_etag | auth | any …;
nginx作为代理服务器接收到从被代理服务器发送的响应报文后,在何种条件下启用压缩功能的;off:对代理的请求不启用
no-cache, no-store,private:表示从被代理服务器收到的响应报文首部的Cache-Control的值为此三者中任何一个,则启用压缩功能;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;
ngz_http_ssl_module模块
实现https功能的模块
实现https模板
server {
listen 443 ssl; #监听443端口并强制使用ssl连接
server_name www.magedu.com;
root /vhosts/ssl/htdocs;
ssl on; #开启ssl功能
ssl_certificate /etc/nginx/ssl/nginx.crt; #当前虚拟主机使用PEM格式的证书文件
ssl_certificate_key /etc/nginx/ssl/nginx.key; #当前虚拟主机与其证书匹配的私钥文件
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; #支持ssl协议版本,默认为后三个;
ssl_session_cache shared:sslcache:20m; #使用openssl内建的缓存,此缓存为每worker进程私有。
ssl_session_timeout 5m; #客户端一侧的连接可以服用ssl session cache中缓存的ssl参数的有效时长;
}
示例:
1 | [root@10-10-10-4 ssl]#vi /etc/nginx/nginx.conf |
ngx_http_rewrite_module模块
将用户请求的URI基于regex所描述的模式进行检查,而后完成替换,可用在server,location,if语句块内。
- rewrite regex replacement [flag]
将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为replacement指定的新的URI;
注意:如果在同一级配置块中存在多个rewrite规则,name会自上而下逐个检查,被某条规则替换完成后,会开始新一轮的替换检查,因此,隐含有循环机制;[flag]所表示的标志位用于控制此循环机制;
如果replacement是以http://或https://开头,则替换结果会直接以重定向方式返回给客户端;
[flag]
last:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环;
break:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环;
redirect:重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;
permanent:重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;
URL重定向示例:将所有以/bbs/开始的请求都将/bbs/重写为/forum/开头的请求。
1 | ~]# vi /etc/nginx/nginx.conf |
将对www.msq.com/bbs/和www.msq.com/forum/的请求重写到forum.msq.com上
1 | ~]# vi /etc/nginx/nginx.conf |
return
return code [text];
return code URL;
return URL;
Stops processing and returns the specified code to a client.rewrite_log on | off;
是否开启重写日志;if (condition) { … }
引入一个新的配置上下文 ;条件满足时,执行配置块中的配置指令;server, location;condition:
比较操作符:== != ~:模式匹配,区分字符大小写; ~\*:模式匹配,不区分字符大小写; !~:模式不匹配,区分字符大小写; !~\*:模式不匹配,不区分字符大小写;
文件及目录存在性判断:
-e, !-e -f, !-f -d, !-d -x, !-x
set $variable value;
用户自定义变量;
ngx_http_referer_module模块
The ngx_http_referer_module module is used to block access to a site for requests with invalid values in the “Referer” header field.
- valid_referers none|blocked|server_names|string…;
定义referer首部的合法可用值可配置在server,location上下文。none:请求报文首部没有referer首部;
blocked:请求报文的referer首部没有值;
server_names:参数,其可以有值作为主机名或主机名模式;
arbitrary_string:直接字符串,但可使用作通配符;
regular expression:被指定的正则表达式模式匹配到的字符串;要使用~打头,例如 ~..magedu.com;
示例:
valid_referers none blocked server_names
*.example.com example.* www.example.org/galleries/
~\.google\.;
if ($invalid_referer) {
return 403;
}
Nginx作为代理服务器
ngx_http_proxy_module模块
与代理相关的模块,nginx作为代理服务器时,支持多种协议,在面向客户端时,支持http,mail等协议;
正向代理:代表的是客户端,去请求服务器,需要客户端配置,客户端请求的是真实服务器地址,但是通过代理服务器发出。类似于SNAT的作用,但是DNAT是工作在3、4层,而Nginx作为代理服务器是工作在应用层。
反向服务器:代表的是服务器端,客户端无需配置,客户端访问的是代理服务器,由代理服务器去后端查找到资源并返回给客户端,而客户端对此无所感知。就像DNAT一样。
- proxy_pass URL;
可用于location,if in location,limit_except上下文
注意:proxy_pass后面的路径不带URI时,其会将location到的URI传递给后端主机;
proxy_pass后面的路径是一个URI时,其会将location到的URI替换为proxy_pass的URI。
示例1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17server {
...
server_name HOSTNAME;
location /uri/ {
proxy_pass http://hos[:port];
}
...
}
server {
...
server_name HOSTNAME;
location /uri/ {
proxy_pass http://host/new_uri/;
}
...
}
如果location定义其URI时使用了正则表达式的模式,或在if语句或limit_except中使用proxy_pass指令,则proxy_pass之后必须不能使用URI;此时用户请求时传递的URI将直接附加在代理到服务之后
示例:
1 | server { |
proxy_set_header field value;
设定发往后端主机的请求报文的请求首部的值;
可配置在http,server,location上下文。proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
在代理服务器使用proxy_set_header X-Real-IP $remote_addr;然后被代理服务器设置LogFormat时加上X-Real-IP变量就可以记录客户端的真实ip。
LogFormat “%{X-Real-IP}i %l %u %t "%r" %>s %b” commonproxy_cache_path;
定义可用于proxy功能的缓存,
只可配置在http上下文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];
proxy_cache zone|off;
指明要调用的缓存,或关闭缓存机制;
可配置在server,location上下文proxy_cache_key string;
缓存中用于”键”的内容
默认值为:
proxy_cache_key $csheme$proxy_host$request_uri;proxy_cache_valid [code…] time;
定义对特定响应码的响应内容的缓存时长。可配置在http,server,location中。定义带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;
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 …;
Determines in which cases a stale cached response can be used when an error occurs during communication with the proxied server.
对哪些类型的过期的资源可以使用缓存应答,off为不是用过期缓存应答。proxy_cache_methods GET | HEAD | POST …;
If the client request method is listed in this directive then the response will be cached. “GET” and “HEAD” methods are always added to the list, though it is recommended to specify them explicitly.proxy_hide_header field;
By default, nginx does not pass the header fields “Date”, “Server”, “X-Pad”, and “X-Accel-…” from the response of a proxied server to a client. The proxy_hide_header directive sets additional fields that will not be passed.proxy_connect_timeout time;
Defines a timeout for establishing a connection with a proxied server. It should be noted that this timeout cannot usually exceed 75 seconds.
默认60s,最长为75s;proxy_read_timeout time;
Defines a timeout for reading a response from the proxied server. The timeout is set only between two successive read operations, not for the transmission of the whole response.proxy_send_timeout time;
Sets a timeout for transmitting a request to the proxied server. he timeout is set only between two successive write operations, not for the transmission of the whole request. If the proxied server does not receive anything within this time, the connection is closed.
nginx代理服务器配置示例
1 | ~]#vi /etc/nginx/nginx.conf |
nginx的缓存在负载均衡器意外宕机后,如果修复故障,则缓存依然有效。
ngx_http_headers_module模块
The ngx_http_headers_module module allows adding the “Expires” and “Cache-Control” header fields, and arbitrary fields, to a response header.
向由代理服务器响应给客户端的响应报文添加自定义首部,或修改指定首部的值。
可配置于http, server, location, if in location语句块
add_header name value [always];
添加自定义首部add_header X-Via $server_addr;
add_header X-Accel $server_name;expires [modified] time;
用于定义Expire或Cache-Control首部的值;
expires epoch | max | off;
ngx_http_fastcgi_module模块
fpm:fastcgi process manager fastcgi协议进程管理
The ngx_http_fastcgi_module module allows passing requests to a FastCGI server.此模块允许将请求转发给fastcgi服务器。
- fastcgi_pass address;
address为fastcgi server的地址:端口,但是不能加协议;可配置于location,if in location; - fastcgi_index name;
fastcgi默认的主页资源 - fastcgi_param parameter value [if_not_empty];
Sets a parameter that should be passed to the FastCGI server. The value can contain text, variables, and their combination.
配置示例1:(前提:配置好fpm server和mariadb-server服务;)
1 | ~]#vi /etc/nginx/nginx.conf |