NGINX介绍及参数

来源:互联网 发布:android编程语言 编辑:程序博客网 时间:2024/05/16 10:22

Nginx("engine x")是一个IMAP/POP3/SMTP代理服务器,也是一个高性能的 HTTP 和 反向代理服务器,但现在大多数情况下都是用来做静态web服务器和反向代理服务器,在作为反向代理服务器的时候,Nginx可以对后端的real server做负载均衡,基于应用层的负载均衡,但是他仅支持一些常见的协议,如:http ,mysql, ftp, smtp.

         相较apache来说,Nginx在静态web,反向代理,性能,高并发等功能上比apache要强大,但是apache在稳定性,动态网站的方面比Nginx优秀.随着互联网的规模越来越大,apache已经解决不了C10k(并发访问量超过10k)的问题了,所以出现了新的应用程序,就如Nginx,目前Nginx的稳定版是1.4.*系列.

Nginx的特性:

基本功能:

       静态资源的web服务器,能缓存打开的文件描述符

       可以做反向代理服务器,缓存,负载均衡

       支持FastCGI

       静态模块化机制,非DSO机制,支持多种过滤器,如gzip,SSI和图像大小调整等

       支持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_connections
 13: }
 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 port 
 22:         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.html
 36:         #
 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 port 
 46:        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.com 
 53: (2) 左侧通配符匹配;*.magedu.com
 54: (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中可以有多个location
 60: location @name { ... }
 61: 功能:允许根据用户请求的URI来匹配指定的各location以进行访问配置;匹配到时,将被location块中的配置所处理;比如:http://www.magedu.com/images/logo.gif /images/logo.gif/就是URI
 62:          =:精确匹配;优先级最高
 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,location
  3: 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方法。上下文:location
  2:                          如: 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, location
  8: limit_rate speed;                   #限制客户端每秒钟传输的字节数;默认为0,表示没有限制;上下文:http, server, location, if in location
  9: limit_rate_after time;              #nginx向客户发送响应报文时,如果时长超出了此处指定的时长,则后续的发送过程开始限速;如:下载站上下文:http, server, location, if in location

文件操作的优化

  1: sendfile on|off是否启用sendfile功能;由内核直接响应用户请求,默认off上下文:http, server, location, if in location
  2: aio on|off是否启用aio功能;完全异步
  3: open_file_cache max=N [inactive=time]|off是否打开文件缓存功能;上下文:http, server, location
  4:                 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, location
 12: 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, location
  4: resover_timeout time;指定DNS解析超时时长,默认为30s,建议5秒??; 上下文:http, server, location
  5: 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:       #客户端IP
  6: $remote_port:       #客户端Port
  7: $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.0
 14: $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/a        
  5: }

访问控制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_names
 13:                *.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: last
  6: 停止执行当前这一轮的ngx_http_rewrite_module指令集,然后查找匹配改变后URI的新location;
  7: break
  8: 停止执行当前这一轮的ngx_http_rewrite_module指令集;
  9: redirect
 10: 在replacement字符串未以“http://”或“https://”开头时,使用返回状态码为302的临时重定向;
 11: permanent
 12: 返回状态码为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/image
 32:         }   
 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: 2 
  5: server accepts handled requests
  6:         2        2       1 
  7: Reading: 0 Writing: 1 Waiting: 1 
  8: 
  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 header
 12: writing -- nginx reads request body, processes request, or writes response to a client
 13: 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: }
0 0
原创粉丝点击