初识nginx ing


大纲

nginx简介

nginx特性

nginx基本功能

nginx的程序架构

nginx的安装和配置

nginx核心模块

nginx标准模块

nginx第三方模块

官网:http://nginx.org/

nginx简介

Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个IMAP/POP3/SMTP代理服务器。 Nginx 是由 Igor Sysoev为俄罗斯访问量第二的 Rambler.ru 站点开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

在高连接并发的情况下,NginxApache服务器不错的替代品。能够支持高达 50,000 个并发连接数的响应,感谢Nginx为我们选择了 epoll and kqueue作为开发模型。

Nginx作为负载均衡服务器:Nginx 既可以在内部直接支持 Rails 和 PHP 程序对外进行服务,也可以支持作为 HTTP代理服务器对外进行服务。Nginx采用C进行编写,不论是系统资源开销还是CPU使用效率都比 Perlbal 要好很多。

作为邮件代理服务器:Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器),Last. fm 描述了成功并且美妙的使用经验。

Nginx 是一个安装非常的简单,配置文件非常简洁(还能够支持perl语法),Bugs非常少的服务器:Nginx 启动特别容易,并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够不间断服务的情况下进行软件版本的升级。


nginx特性


    模块化设计,较好的扩展性;

    高可靠性

 master/worker

    支持热部署

       不停机更新配置文件、更换日志文件、更新服务器程序版本;

    低内存消耗

10000个keep-alive连接模式下的非活动连接仅消耗2.5M内存;

    事件驱动event-driven, aio, mmap



nginx基本功能


静态资源的web服务器;

      http协议反向代理服务器;

      pop3/imap4协议反射代理服务器;

      FastCGI(lnmp), uWSGI等协议;

      模块化(非DSO),著名有zip, SSL, ...;

     web服务器相关的功能:

                虚拟主机、keepalive、访问日志、url rewrite、路径别名、基于ip及用户的访问控制、支付速率限制及并发数限制,...;


nginx程序架构


初识nginx ing_第1张图片


nginx工作原理

1、master/worker

    一个master进程,可生成一个或多个worker进程,加载配置文件、管理worker进程、平滑升级

    worker:用来处理请求(http服务、http代理、fastcgi代理、...)

2、模块

 模块配置好之后由master进程加载,并在创建worker进程时生效

    核心模块: core module 

    标准模块:

        Standard HTTP modules

        Optional HTTP modules

        Mail modules

    第三方模块

注:引入模块会引入配置指令和变量


nginx的安装及配置

默认没有在base源中提供,因此可以在nginx的官方站点下载http://nginx.org/packages/


nginx的安装:

~]# yum -y install pcre-devel openssl-devel zlib-devel


编译安装:

~]# ./configure \
--prefix=/usr/local
--sbin-path=/usr/sbin/nginx
--conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--pid-path=/var/run/nginx.pid
--lock-path=/var/run/nginx.lock
--http-client-body-temp-path=/var/cache/nginx/client_temp
--http-proxy-temp-path=/var/cache/nginx/proxy_temp
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
--http-scgi-temp-path=/var/cache/nginx/scgi_temp
--user=nginx
--group=nginx
--with-http_ssl_module
--with-http_realip_module
--with-http_addition_module
--with-http_sub_module
--with-http_dav_module
--with-http_flv_module
--with-http_mp4_module
--with-http_gunzip_module
--with-http_gzip_static_module
--with-http_random_index_module
--with-http_secure_link_module
--with-http_stub_status_module
--with-http_auth_request_module
--with-threads
--with-stream
--with-stream_ssl_module
--with-http_slice_module
--with-file-aio
--with-http_v2_module
~]# make && make install


配置文件及指令


        配置文件 的组成部分:

                主配置文件:nginx.conf

也可以用此语句:include  conf.d/*.conf

                facscgi, scgi, uwscgi的相关配置

                mime.types

        配置指令(必须以分号结尾):

                directive  value1 [value2...];

                支持使用变量:

内置变量:由模块引入,可直接引用;

自定义变量:set  variable_name  value;

引用变量:$variable_name

        配置文件结构:

main block  #全局配置;
event {
...
}  #事件驱动的相关配置;
http {
...
}  #http协议的相关配置
mail {
...
}  #mail相关的配置;


http相关的配置:

  http {
       ...
        ...
server {
...
server_name
root
alias 
location /uri/ {
...
}
...
}
server {
...
...
}
}


cat /etc/nginx/nginx.conf


main block(由核心模块引入):

    配置指令的类别:

    正常运行必备的配置;

    优化性能的配置;

    用于调试、定位问题的配置;


正常运行必备的配置:

    1、user  USERNAME  [GROUPNAME];

    指定用于运行worker进程的用户和组;


    user  nginx  nginx;


    2、pid  /PATH/TO/PID_FILE;

    指定nginx进程的pid文件路径;


    pid  /var/run/nginx.pid;


    3、worker_rlimit_nofile number;

    单个worker进程所能够打开的最大文件数;


性能优化相关的配置:

    1、 worker_processes number | auto;

    worker的进程数;通常应该为CPU的核心数减1;


    2、worker_cpu_affinity cpumask ...;

     worker_cpu_affinity auto [cpumask]; 

     

     CPUMASK:

    0000 0001

    0000 0010

    0000 0100

    0000 1000

    0001 0000

    ...

    3、worker_priority nice;worker进程nice值:

    [-20,19]

    100-139


调试、定位问题:

    1、daemon on | off;

    是否以守护进程方式启动nginx进程;


    2、master_process on | off;

    是否以master/worker模型启动nignx进程;


    3、error_log file | stderr | syslog:server=address[,parameter=value] | memory:size     [debug | info | notice | warn | error | crit | alert | emerg];

        

    错误日志文件的记录方式,及其日志级别:

    方式:

        file  /PATH/TO/SOME_LOG_FILE;

        stderr:发送到错误输出;

        syslog:server=address[,parameter=value]:发送给syslog服务器;

        memory:size

 

        日志级别:

            debug依赖于configure时的--with-debug选项;



nginx的核心模块

参考官网:http://nginx.org/en/docs/http/ngx_http_core_module.html


nginx.conf:

main block

events {

...

}


1、worker_connections number;

    每个worker进程所能够并发打开的最大连接数;


    worker_processes * worker_connections


2、use method;

    指明并发连接请求处理时使用的方法;


    use  epoll;


3、accept_mutex on | off;

    启用时,表示用于让多个worker轮流地、序列化地响应新请求;




http {

...

}


定义套接字相关功能


1、server { ... }

配置一个虚拟主机;


server {

listen PORT;

server_name  HOSTNAME; 

root /PATH/TO/DOCUMENTROOT;

...

}


注意:

(1) 基于port的虚拟主机:

listen指令要使用不同的端口;

(2) 基于Hostname的虚拟主机;

server_name指令指向不同的主机名;

(3) 基于ip的虚拟主机:

listen IP:PORT;


2、listen address[:port] [default_server] [ssl] [backlog=number] [rcvbuf=size] [sndbuf=size];

     listen port [default_server] [ssl];

     listen unix:path [default_server] [ssl] ;

     

default_server:默认虚拟主机;

ssl:限制只能通过ssl连接提供服务;

backlog:后缓队列的长度;

rcvbuf:接收缓冲大小;

sndbuf:发送缓冲区大小;


3、server_name name ...;

指明当前server的主机名;后可跟一个或空白字符分隔的多个主机;

支持使用*任意长度的任意字符;

支持~起始的正则表达式模式字符串;


应用策略:

(1) 首先精确匹配;

(2) 左则*通配符匹配;

(3) 右侧*通配符匹配;

(4) 正则表达式模式匹配;


server_name  www.magedu.com;


server_name *.magedu.com;


server_name  www.magedu.*;


server_name ~^.*\.magedu\..*$;


mail.magedu.com, www.magedu.com


4、tcp_nodelay  on|off;

对keepalived模式下的连接是否启用TCP_NODELAY选项;


5、sendfile on | off;

是否启用sendfile功能;



定义路径相关配置

6、root path;

设置web资源路径映射;用于指明用户请求的url所对应的本地文件系统上的文档所在目录路径;

可用上下文:http, server, location, if


7、location [ = | ~ | ~* | ^~ ] uri { ... }

     location @name { ... }

     

     根据用户请求的URI来匹配定义的location,匹配到时,此请求将被相应的location块中的指令所处理;

     

server {

...

location {


}

location {

...

}

}


=:URI精确匹配;

~:做正则表达式模式匹配,区分字符大小写;

~*:做正则表达式模式匹配,不区分字符大小写;

^~:对URI的左半部分做匹配检查,不区分字符大小写;


匹配优先级:=、^~、~/~*、不带符号;


8、alias path;

定义路径别名,文档映射的一种机制;仅能用于location上下文;


alias  /bbs/  /web/forum/


http://www.magedu.com/bbs/a.jpg


location  /bbs/  {

alias  /web/forum/;

}


/web/forum/a.jpg


location  /bbs/  {

root  /web/forum/;

}


/web/forum/bbs/a.jpg



注意:

root指令:给定的路径对应于location中的/uri/左侧的/;

alias指令:给定的路径对应于location中的/uri/右侧的/;


9、index file ...;

可用位置:http, server, location


默认主面;


10、error_page code ... [=[response]] uri;

根据用户请求的资源的http响应的状态码实现错误页重定向;


http://www.magedu.com/hello.html --> 因为资源不存在而被改为对

http://www.magedu.com/404.html


11、try_files file ... uri;

      try_files file ... =code; 

尝试查找第1至第N-1个文件,第一个即为返回给请求者的资源;若1至N-1文件都不存在,则跳转至最一个uri(必须不能匹配至当前location,而应该匹配至其它location,否则会导致死循环);



定义客户端请求的相关配置


12、keepalive_timeout timeout [header_timeout];

设定保持连接的超时时长,0表示禁止长连接 ;默认为75s;


13、keepalive_requests number;

在一次长连接上所允许请求的资源的最大数量,默认为100;


14、keepalive_disable none | browser ...;

对哪种浏览器禁用长连接;


15、send_timeout time;

向客户端发送响应报文的超时时长; 特别地,是指两次写操作之间的间隔时长; 


16、client_body_buffer_size size;

用于接收客户端请求报文的body部分的缓冲区大小;默认为16k;超时此大小时,其将被暂存到磁盘上;


17、client_body_temp_path path [level1 [level2 [level3]]];

设定用于存储客户端请求报文的body部分的临时存储路径及子目录结构和数量;


/var/tmp/body  2 1 2

00-ff



对客户的请求进行限制的相关配置:

18、limit_rate rate;

限制响应给客户端的传输速率,单位是bytes/second,0表示无限制;


19、limit_except method ... { ... };

限制对指定的请求方法之外的其它方法的使用客户端;


limit_except GET POST {

allow  172.18.0.0/16;

deny all;

}


表示除了GET和POST之外的其它方法仅允许172.18.0.0/16中的主机使用;


文件操作优化的配置:

20、aio on | off | threads[=pool];

是否启用aio功能;


21、directio size | off;


22、open_file_cache off;

open_file_cache max=N [inactive=time];

nginx可以缓存以下三种信息:

(1) 文件的描述符、文件大小和最近一次的修改时间;

(2) 打开的目录的结构;

(3) 没有找到的或者没有权限访问的文件的相关信息;


max=N:可缓存的缓存项上限;达到上限后会使用LRU算法实现缓存管理;


inactive=time:缓存项的超时时长,在此处指定的时长内未被命中的缓存项即为非活动项;


23、open_file_cache_errors on | off;

是否缓存查找时发生错误的文件一类的信息;


24、open_file_cache_min_uses number;

在open_file_cache指令的inactive参数指定的时长内,至少命中此处指定的次数方可不被归类到非活动项;


25、open_file_cache_valid time;

缓存项有效性的检查频率;默认是60s;


ngx_http_access_module模块:

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


26、allow address | CIDR | unix: | all;

27、deny address | CIDR | unix: | all;


可用上下文:http, server, location, limit_except


ngx_http_auth_basic_module模块:

28、auth_basic string | off;

使用basic机制进行用户认证;


29、auth_basic_user_file file;

认证用的账号密码文件;


文件格式:

name:password:commet


密码格式:

htpasswd命令;


location /admin/ {

auth_basic "Admin Area";

auth_basic_user_file /etc/nginx/.ngxpasswd;

}

ngx_http_stub_status_module模块:

用于输出nginx的基本状态信息;


Active connections: 1 

server accepts handled requests

155 155 298 

Reading: 0 Writing: 1 Waiting: 0


Active connections:  处于活动状态的客户端连接的数量;

accepts:已经接受的客户端请求的总数;

handled:已经处理完成的客户端请求的总数;

requests:客户端发来的总的请求数;

Reading:处于读取客户端请求报文首部的连接数;

Writing:处于向客户端发送响应报文过程中的连接数;

Waiting:处于等待客户端发出请求的空闲连接数;


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.


30、valid_referers none | blocked | server_names | string ...;

定义合法的referer数据;


none:请求报文首部没有referer首部;

blocked:请求报文的referer首部没有值;

server_names:其值是主机名;

arbitrary string:直接字符串,可以使用*作为通配符;

regular expression:被指定的正则表达式模式匹配到的字符串;要使用~起始;


valid_referers none blocked server_names *.magedu.com magedu.* ~\.magedu\.;


if ($invalid_referer) {

return 403;

}



你可能感兴趣的:(nginx)