Nginx("engine x")是一个IMAP/POP3/SMTP代理服务器,也是一个高性能的 HTTP 和 反向代理服务器,但如今大多数状况下都是用来作静态web服务器和反向代理服务器,在做为反向代理服务器的时候,Nginx能够对后端的real server作负载均衡,基于应用层的负载均衡,可是他仅支持一些常见的协议,如:http ,mysql, ftp, smtp.javascript
相较apache来讲,Nginx在静态web,反向代理,性能,高并发等功能上比apache要强大,可是apache在稳定性,动态网站的方面比Nginx优秀.随着互联网的规模愈来愈大,apache已经解决不了C10k(并发访问量超过10k)的问题了,因此出现了新的应用程序,就如Nginx,目前Nginx的稳定版是1.4.*系列.css
Nginx的特性:html
基本功能:java
静态资源的web服务器,能缓存打开的文件描述符node
能够作反向代理服务器,缓存,负载均衡mysql
支持FastCGInginx
静态模块化机制,非DSO机制,支持多种过滤器,如gzip,SSI和图像大小调整等web
支持SSL正则表达式
扩展功能:算法
支持基于名称和IP作虚拟主机
支持keepalive
支持平滑的升级,平滑的配置文件更新
支持定制访问日志,支持日志缓存以提升性能
支持url rewrite
支持路径别名
支持基于IP和用户认证
支持速率限制,并发限制
Nginx的基本架构
Nginx会启动一个master进程和多个worker线程/进程,每一个worker进程能够响应多个请求,启动的worker数量能够自行设置,通常而言,设置的worker数量应该比cpu的核心数少一到两个,如24个核心的cpu,应该设置22-23个worker进程数,Nginx是基于事件驱动:kqueue,epoll(Linux),/dev/poll,也支持消息通知机制:select,poll,rt signals;支持sendfile:服务器响应请求时,由内核直接响应,而不用通过用户空间.支持文件AIO,异步IO,支持mmap,内存映射.
Nginx的模块,这里只介绍http模块
Nginx是高度模块化的程序,其中包含Nginx的核心模块(编译时默认都安装),http的标准模块以及http的可选模块
Nginx的核心模块配置内别
核心段
1: #user nobody; #以哪一个用户的身份运行worker进程,2: worker_processes 1; #启动的worker的数量,性能优化关键点3:4: #error_log logs/error.log; #错误日志文件及其级别;默认为error级别;调试时可使用debug级别,但要求在编译时必须使用--with-debug启用debug功能;5: #error_log logs/error.log notice; #同上,可是级别为notice
6: #error_log logs/error.log info; #同上,可是级别为 info
7:8: #pid logs/nginx.pid; #指定Nginx的pid文件9:10:11: events { #12: worker_connections 1024; #worker进程的个数;一般其数值应该为CPU的物理核心数减1或减2;Nginx的最大并发数为worker_processes*worker_connections13: }14: ----------------------如下都是默认不存在的配置-------------------------15: -------性能优化相关-------16:17: worker_rlimit_nofile 9999; #指定一个worker进程所可以打开的最大文件句柄数,可使用ulimit -n查看单个文件能够打开的最大句柄数,(socket链接也算在里面)。系统默认值1024,此值需大于等于worker_connections,可是若是是代理服务器,此值应大于等于worker_connections的两倍18: worker_rlimit_sigpending 12; #设定每一个用户可以发往worker进程的信号的数量19: worker_cpu_affinity cpumask; #与上面的worker_processes有关,让worker运行在指定的cpu上,若有4颗cpu,4个process,那就分别是0001,0010,0100,1000,表示第0,1,2,3颗cpu,性能优化关键点20: ssl_engine ssldevice; #在存在ssl硬件加速器的服务器上,指定所使用的ssl硬件加速设备;21: timer_resolution t; #每次内核事件调用返回时,都会使用gettimeofday()来更新nginx缓存时钟;timer_resolution用于定义每隔多久才会由gettimeofday()更新一次缓存时钟;x86-64系统上,gettimeofday()代价已经很小,能够忽略此配置;22: worker_priority number; #worker的优先级,值越小,优先级越高,对于性能的加强也是很关键的(-20,20),默认是0,对系统的性能加强很关键23: -------事件相关-----------24: 须要定义在 events { } 里面25: accept_mutex [on|off]; #是否打开Ningx的负载均衡锁;此锁可以让多个worker进轮流地、序列化地与新的客户端创建链接;而一般当一个worker进程的负载达到其上限的7/8,master就尽量再也不将请求调度此worker;默认为on
26: lock_file /path/to/lock_file; #这是accept_mutex的锁文件,若是accept_mutex为off,这项就没用了
27: accept_mutex_delay #ms; #在accept锁模式中,一个worker进程为取得accept锁的等待时长;若是某worker进程在某次试图取得锁时失败了,至少要等待#ms才能再一次请求锁;默认是500毫秒28: multi_accept on|off; #是否容许worker一次性地响应多个用户请求;默认为Off,一个链接一个链接的创建;
29: use [epoll|rtsig|select|poll]; #定义使用的事件模型,建议让nginx自动选择;在Linux中通常(默认)都选择epoll
30: ------用于调试、定位问题--31: 只在调试时使用32: daemon on|off; #是否让ningx运行后台;默认为on,调试时能够设置为off,使得全部信息去接输出控制台;
33: master_process on|off; #是否以master/worker模式运行nginx;默认为on;调试时可设置off以方便追踪;
http段
1: ----主要有三段:http段,server段,location段-------2: http {3: include mime.types;4: default_type application/octet-stream;5:6: #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
7: # '$status $body_bytes_sent "$http_referer" '
8: # '"$http_user_agent" "$http_x_forwarded_for"';
9:10: #access_log logs/access.log main;11:12: sendfile on;
13: #tcp_nopush on;
14:15: #keepalive_timeout 0;16: keepalive_timeout 65;17:18: #gzip on;
19:20: server { #定义虚拟主机21: listen 80; #监听的端口listen address[:port];listen port22: server_name localhost; #定义基于主机名或IP的虚拟主机,可跟多个主机名23: server_name_hash_bucket_size #快速主机名查找使用hash主机名24:25: #charset koi8-r;26:27: #access_log logs/host.access.log main;28:29: location / {30: root html; #设置web资源的路径,能够放在http,server和location中31: index index.html index.htm; #定义默认主页,自左向右匹配32: }33:34: #error_page 404 [=200] /404.html; #错误页面重定向,[=200表示请求状态码也编程200]35: # redirect server error pages to the static page /50x.html36: #37: error_page 500 502 503 504 /50x.html;38: location = /50x.html {39: root html;40: }41: }42: -----详细说明-------43: listen #仅能在server段44: listen address[:port];45: listen port46: default_server:定义此server为http中默认的server;若是全部的server中没有任何一个listen使用此参数,那么第一个server即为默认server;47: rcvbuf=SIZE: 接收缓冲大小;48: sndbuf=SIZE: 发送缓冲大小;49: ssl: https server;50: server_name [...];51: server_name能够跟多个主机名,名称中可使用通配符和正则表达式(一般以~开头);当nginx收到一个请求时,会取出其首部的server的值,然后跟众server_name进行比较;比较方式:52: (1) 先作精确匹配;www.magedu.com53: (2) 左侧通配符匹配;*.magedu.com54: (3) 右侧通配符匹配;www.abc.com, www.*55: (4) 正则表达式匹配: ~^.*\.magedu\.com$56: server_name_hash_bucket_size 32|64|128;57: 为了实现快速主机查找,nginx使用hash表来保存主机名;系统默认没有此项,也不是过重要58: ---------如下均为location中的参数------59: location [ = | ~ | ~* | ^~ ] uri { ... } 只能在server和location中,一个server中能够有多个location60: location @name { ... }61: 功能:容许根据用户请求的URI来匹配指定的各location以进行访问配置;匹配到时,将被location块中的配置所处理;好比:http://www.magedu.com/images/logo.gif /images/logo.gif/就是URI62: =:精确匹配;优先级最高63: ~:正则表达式模式匹配,匹配时区分字符大小写64: ~*:正则表达式模式匹配,匹配时忽略字符大小写65: ^~: URI前半部分匹配,不检查正则表达式66: 让咱们用一个例子解释上面的说法:67: location = / {68: [ configuration A ]69: }70:71: location / {72: [ configuration B ]73: }74:75: location /documents/ {76: [ configuration C ]77: }78:79: location ^~ /images/ {80: [ configuration D ]81: }82:83: location ~* \.(gif|jpg|jpeg)$ {84: [ configuration E ]85: }86: 请求“/”匹配配置A, 请求“/index.html”匹配配置B, 请求“/documents/document.html”匹配配置C, 请求“/images/1.gif”匹配配置D, 请求“/documents/1.jpg”匹配配置E。87:88: 1.alias path
89: 只能用于location中,用于路径别名;90: location /i/ {91: alias /data/w3/images/;
92: }93: “访问/i/top.gif时”将由/data/w3/images/top.gif文件来响应。94: 2.try_files path1 [path2 ...] uri;自左至右尝试读取由path所指定路径,在第一次找到即中止并返回;若是全部path均不存在,则返回最后一个uri;95: location ~* ^/documents/(.*)$ {96: root /www/htdocs;97: try_files $uri /docu/$1 /temp.html;98: }
网络链接相关的设置
1: keepalive_timeout time; #保持链接的超时时长;默认为75秒;能够定义在http, server, location中2: keepalive_requests n; #在一次长链接上容许承载的最大请求数;上下文:http,server,location3: keepalive_disable [msie6 | safari | none ]; #对指定的浏览器禁止使用长链接;有些浏览器不支持长链接4: tcp_nodelay on|off; #对keepalive链接是否使用TCP_NODELAY选项;默认on;把多个确认报文合成一个响应,确认延迟
5: client_header_timeout time; #读取http请求首部的超时时长;6: client_body_timeout time; #读取http请求包体的超时时长;7: send_timeout time; #发送响应的超时时长;
对客户端请求的限制:
1: limit_except method ... { ... } #指定对范围以外的其它方法的访问控制;指定method为GET方法的同时,nginx会自动添加HEAD方法。上下文:location2: 如: limit_except GET {
3: allow 192.168.1.0/32;4: deny all;5: }6: 请留意上面的例子将对除GET和HEAD方法之外的全部HTTP方法的请求进行访问限制。7: client_max_body_size SIZE; #http请求包体的最大值;经常使用于限定客户所可以请求的最大包体;根据请求首部中的Content-Length来检测,以免无用的传输;上下文: http, server, location8: limit_rate speed; #限制客户端每秒钟传输的字节数;默认为0,表示没有限制;上下文:http, server, location, if in location9: limit_rate_after time; #nginx向客户发送响应报文时,若是时长超出了此处指定的时长,则后续的发送过程开始限速;如:下载站上下文: http, server, location, if in location
文件操做的优化
1: sendfile on|off是否启用sendfile功能;由内核直接响应用户请求,默认off上下文:http, server, location, if in location2: aio on|off是否启用aio功能;彻底异步
3: open_file_cache max=N [inactive=time]|off是否打开文件缓存功能;上下文: http, server, location4: max: 缓存条目的最大值;当满了之后将根据LRU(最近最少使用)算法进行置换;5: inactive: 某缓存条目在指定时长时没有被访问过期,将自动被删除;默认为60s;6: 缓存的信息包括:7: 文件句柄、文件大小和上次修改时间;8: 已经打开的目录结构;9: 没有找到或没有访问权限的信息;10: open_file_cache_errors on|off是否缓存文件找不到或没有权限访问等相关信息;默认off;上下文:http, server, location
11: open_file_cache_valid time;多长时间检查一次缓存中的条目是否超出非活动时长,默认为60s; 上下文:http, server, location12: open_file_cache_min_use #;在inactive指定的时长内被访问超此处指定的次数地,才不会被删除;默认1分钟;上下文:http, server, location
对客户端请求的特殊处理
1: ignore_invalid_headers on|off是否忽略不合法的http首部;默认为on; off意味着请求首部中出现不合规的首部将拒绝响应;只能用于server和http;
2: log_not_found on|off; 是否将文件找不到的信息也记录进错误日志中;默认为on;上下文:http, server, location
3: resolver address; 指定nginx使用的dns服务器地址;上下文: http, server, location4: resover_timeout time;指定DNS解析超时时长,默认为30s,建议5秒??; 上下文:http, server, location5: server_tokens on|off;是否在错误页面中显示nginx的版本号;默认on,上下文: http, server, location
http核心模块的内置变量:
1: $uri: #当前请求的uri,不带参数;参数 ?=12等之类的2: $request_uri: #请求的uri,带完整参数;3: $host: #http请求报文中host首部;若是请求中没有host首部,则以处理此请求的虚拟主机的主机名代替;4: $hostname: #nginx服务运行在的主机的主机名;5: $remote_addr: #客户端IP6: $remote_port: #客户端Port7: $remote_user: #使用用户认证时客户端用户输入的用户名;8: $request_filename: #用户请求中的URI通过本地root或alias转换后映射的本地的文件路径;用的不少9: $request_method: #请求方法10: $server_addr: #服务器地址11: $server_name: #服务器名称12: $server_port: #服务器端口13: $server_protocol: #服务器向客户端发送响应时的协议,如http/1.1, http/1.014: $scheme: #在请求中使用scheme, 如https://www.magedu.com/中的https;15: $http_HEADER: #匹配请求报文中指定的HEADER,$http_host匹配请求报文中的host首部16: $sent_http_HEADER: #匹配响应报文中指定的HEADER,例如$http_content_type匹配响应报文中的content-type首部;17: $document_root: #当前请求映射到的root配置;
配置使用nginx:
nginx虚拟主机
1: server {2: listen 80;3: server_name www.a.com;4: root /web/a5: }
访问控制access模块,它只有两个选项 allow和deny
1: server {2: listen 80;3: server_name www.b.org;4: root /web/b;5:6: allow 192.168.0.0/16;7: deny all;8: }
用户认证示例
1: location /admin/ {2: auth_basic "admin";
3: auth_basic_user_file /etc/nginx/.htpasswd;4: root /web/b/;5: }6: 使用htpasswd -c -m /path/to/somefile username 建立密码文件
创建下载站点autoindex,只需autoindex为on就好了,在/web/b/down目录下的不可识别的文件都会被以列表的形式列出来
1: location /down/ {2: autoindex on;
3: root /web/b/;4: }5:
防盗链
1: 该指令的参数能够为下面的内容:2:3: none # 缺乏“Referer”请求头;4: blocked # “Referer” 请求头存在,可是它的值被防火墙或者代理服务器删除; 这些值都不以“http://” 或者 “https://”字符串做为开头;5: server_names # “Referer” 请求头包含某个虚拟主机名;6: 任意字符串 # 定义一个服务器名和可选的URI前缀。服务器名容许在开头或结尾使用“*”符号。 当nginx检查时,“Referer”请求头里的服务器端口将被忽略。7: 正则表达式 # 必须以“~”符号做为开头。 须要注意的是表达式会从“http://”或者“https://”以后的文本开始匹配。8:9: ngx_http_referer_module模块容许拦截“Referer”请求头中含有非法值的请求,阻止它们访问站点。 须要注意的是伪造一个有效的“Referer”请求头是至关容易的, 所以这个模块的预期目的不在于完全地阻止这些非法请求,而是为了阻止由正常浏览器发出的大规模此类请求。 还有一点须要注意,即便正常浏览器发送的合法请求,也可能没有“Referer”请求头。10: 实例:11:12: valid_referers none blocked server_names13: *.example.com example.* www.example.org/galleries/14: ~\.google\.;15:16: if ($invalid_referer) { 若是是以上指定范围外的,则返回 403错误
17: return 403;
18: }
URL rewrite,地址重写
1: rewrite regex replacement [flag]; #上下文 server,location,if
2:3: flag参数能够是其中之一:4:5: last6: 中止执行当前这一轮的ngx_http_rewrite_module指令集,而后查找匹配改变后URI的新location;7: break8: 中止执行当前这一轮的ngx_http_rewrite_module指令集;9: redirect10: 在replacement字符串未以“http://”或“https://”开头时,使用返回状态码为302的临时重定向;11: permanent12: 返回状态码为301的永久重定向。13: 举例:14:15: server {16: ...17: rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;18: rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra last;19: return 403;
20: ...21: }22: 可是当上述指令写在“/download/”的location中时,应使用标志break代替last,不然nginx会重复10轮循环,而后返回错误500:23:24: location /download/ {25: rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;26: rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra break;27: return 403;
28: }29: location /down1/ { #能够没有down1文件夹30: # root /web/b;31: rewrite ^/down1/(.*\.(jpg|gif|png))$ /image/$1 last; #访问网址是www.a.com/down1,实际目录是www.a.com/image32: }33:34: rewrite_log on|off #开启或者关闭将ngx_http_rewrite_module模块指令的处理日志以notice级别记录到错误日志中。默认为off;
35: return code: #用于结束rewrite规则,而且为客户返回状态码;可使用的状态码有204, 400, 402-406, 500-504等;
SSL
1: #2: #server {3: # listen 443;4: # server_name localhost;5:6: # ssl on; #开启ssl引擎
7: # ssl_certificate cert.pem; #证书8: # ssl_certificate_key cert.key; #私钥文件9:10: # ssl_session_timeout 5m; #ssl的超时时间,ssl会话的创建还释放比保持链接更消耗时间,因此若是内存够大而且你网站的粘性比较大,建议时间调长一点11:12: # ssl_protocols SSLv2 SSLv3 TLSv1; #支持的协议13: # ssl_ciphers HIGH:!aNULL:!MD5; #加密算法14: # ssl_prefer_server_ciphers on; #服务端选择倾向的算法
stub_status状态页
1: location /server-status {2: stub_status on;
3: }4: Active connections: 25: server accepts handled requests6: 2 2 17: Reading: 0 Writing: 1 Waiting: 18:9: active connections -- number of all open connections
10: server accepts handled requests -- nginx accepted 2 connections, handled 2 connections (no one was closed just it was accepted), and handles 1 requests (1.8 requests per connection)11: reading -- nginx reads request header12: writing -- nginx reads request body, processes request, or writes response to a client13: waiting -- keep-alive connections, actually it is active - (reading + writing)
gzip压缩页面
1: http {2: gzip on; #开启压缩功能,能够放在http,server
3: gzip_http_version 1.0; #压缩后使用那种http协议构建响应报文4: gzip_comp_level 2; #压缩级别5: gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript application/json; #仅对这些格式的内容进行压缩6: gzip_disable msie6; #对IE6不使用压缩机制7: }