何为Nginx?

  Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。最初是为了解决C10k的问题,由Igor Sysoev为俄罗斯访问量第二的Rambler.ru站点开发的,第一个公开版本0.1.0发布于2004年10月4日。

其特性有:

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

    Nginx代码完全用C语言从头写成,已经移植到许多体系结构和操作系统,包括:Linux、FreeBSD、Solaris、Mac OS X、AIX以及Microsoft Windows。

    模块类型:

      核心模块:core modules

      标准模块:Standard HTTP modules、Optional HTTP modules、Mail modules

      第三方模块

  √高可靠性

    master/worker,一个主进程和多个工作进程。工作进程是单线程的,且不需要特殊授权即可运行;

    master:加载配置文件、管理worker进程、平滑升级...

      worker:http服务,http代理,fastcgi代理...

  √支持热部署

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

  √低内存消耗

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


编译安装Nginx

  [此处以CentOS 6.5编译安装Nginx-1.10.2版本为例进行说明]

  安装前的依赖包(组):

    ①zlib-devel

    ②pcre-devel

    ③openssl-devel

    ④Development Tools & Server Platform Development

  编译三步骤走起:

 ./configure --prefix=/usr/local/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_gunzip_module --with-http_realip_module --with-http_addition_module --with-http_dav_module --with-http_flv_module --with-http_mp4_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的配置

  主配置文件:nginx.conf

  配置指令:必须以分号结尾,且支持使用变量

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

    自定义变量:定义->set variable_name value;引用->$variable_name

  配置文件结构:

    main block(全局配置段)

    events(事件驱动配置段)

    http(http协议配置段)

    mail(mail配置段)

  接下来逐一介绍各配置段:

  main block:

    正常运行必备的配置

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

Syntax:    user user [group];
Default: user nobody nobody;
Context: main

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

Syntax:    pid file;
Default: pid nginx.pid;
Context: main

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

Syntax:    worker_rlimit_nofile number;
Default: —
Context: main

    优化性能的配置

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

Syntax:    worker_processes number | auto;
Default: worker_processes ;
Context: main

        

Syntax:    worker_cpu_affinity cpumask ...;
worker_cpu_affinity auto [cpumask];
Default: —
Context: main

    示例:worker_cpu_affinity 0001,0010 ...;  

/*
CPUMASK:有几颗CPU就有几位二进制数字
0000 0001 第一个CPU
0000 0010 二
0000 0100 三
0000 1000 ... */

        ③worker_priority nice;

          nice值:[-20,19],对应的优先级是100-139;

    用于调试/定位问题的配置

      ①daemon on | off;

       是否以守护进程方式启动nginx进程(默认是on)

       ②master_process on | off;

        是否以master/worker模型启动nginx进程,调试时可关闭此项

       ③error_log file | stderr | syslog:server=address[,parameter=value] | memory:size [level];       

/*错误日志文件的记录方式及日志级别

    方式:
file /PATH/TO/SOME_LOG_FILE
stderr 发送到错误输出
syslog:server=address[,parameter=value] 发送给syslog服务器
memory:size 记录到内存中,可一定程度减轻磁盘IO压力 level:
debug(依赖于configure时的--with-debug选项),info,notice,warn,error,crit,alert,emerg
/*

  events

    ①worker_connections number;

      设定单个worker进程能够打开的最大并发连接数,只能用在events中,默认值是512,受限于worker_rlimit_nofile number所设定的数量       

        当前系统Nginx所能承受的最大并发连接数:worker_processes*worker_connections

      ②use method;

        指明并发连接请求处理时使用的方法(select,poll,epoll...)

     ③accept_mutex on | off;

       是否打开worker的负载均衡机制(worker基于轮询方式处理请求),默认是开启的,依赖于main配置段中的lock_file此项定义的锁文件

  http  

   ngx_http_core_module的核心配置

    A.定义套接字相关功能的配置

      ①server {...}

       配置一个虚拟主机

server {
listen PORT;
server_name HOSTNAME;
root /PATH/TO/DOCUMENTROOT;
} /*
(1)基于PORT的虚拟主机
listen指令要使用不同的端口;
(2)基于Hostname的虚拟主机
server_name指令指向不同的主机名;
(3)基于IP的虚拟主机
listen IP:PORT;
*/

      ②listen

①listen address[:port] [default_server] [ssl] [backlog=number] [rcvbuf=size] [sndbuf=size];
ssl //限制只能通过ssl连接提供服务
default_server //默认虚拟主机
backlog=number //后援队列
rcvbuf=size //接收缓冲大小
sndbuf=size //发送缓冲大小 ②listen port [default_server] [ssl]; ③listen unix:path [default_server] [ssl];
//多用于本地间,基于unix sock通过本地回环接口进行通信(不会经由内核中的协议栈)

         ③server_name name ...;

        指明当前server的主机名,当有多个时,以空白字符分隔,有优先级如下

全名(精确匹配):the exact name

左侧匹配:the longest wildcard name starting with an asterisk, e.g. “*.example.com”

右侧匹配:the longest wildcard name ending with an asterisk, e.g. “mail.*”

正则匹配:the first matching regular expression (in order of appearance in the configuration file),e.g. “~^.*\.example\..*$”

//支持使用*表示任意长度的任意字符
//支持使用~起始的正则表达式模式匹配

        ④tcp_nodelay on | off;

          对keepalived模式下的连接是否启用延迟发送功能,仅能用在http,server,location中,默认是开启的

       ⑤sendfile on | off;

         是否启用sendfile(在内核中构建响应报文)功能(默认关闭),最好启动起来

    B.定义路径相关的配置

      ①root path;       

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

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

       ②location

location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
//根据用户请求的URI来匹配定义的location,匹配到时,此请求将被响应的location块中的指令处理;可用在server和location上下文 其中:
=:URI精确匹配
~:正则表达式模式匹配,区分字符大小写
~*:正则表达式模式匹配,不区分字符大小写
^~:对URI左侧进行正则表达式匹配,不区分字符大小写 //匹配优先级:=>^~>~/~*>不带符号
/*示例*/
location = / {
[ configuration A ]
} location / {
[ configuration B ]
} location /documents/ {
[ configuration C ]
} location ^~ /images/ {
[ configuration D ]
} location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}

        ③alias path;

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

/*示例*/

location /i/ {
alias /data/w3/images/;
}
相当于www.a.com/data/w3/images/ location /i/ {
root /data/w3/images/;
}
相当于www.a.com/data/w3/images/i/ /*
root指令,给定的路径对于location中的/uri/左侧的/;
alias指令,给定的路径对应于location中的/uri/右侧的/;
*/

        ④index file ...;

          默认主页面

          可用上下文:http,server,location

       ⑤error_page code ... [=[response]] uri;       

           根据用户请求的资源的http响应的状态码实现错误页面重定向,[=[response]] 可自定义响应码;

          可用上下文:http,server,location

       ⑥try_files file ... uri;

       try_files file ... =code;

            用在server,location上下文;表示当用户请求的资源不存在时,尝试访问try_files 后面定义的file,可能有多个,第一个没有就访问第二个,以此类推;如果都访问不到,则应用最后的uri

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

      ①keepalive_timeout timeout [header_timeout];      

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

          用在http,server,location上下文

       ②keepalive_requests number;        

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

           用在http,server,location上下文

       ③keepalive_disable none | browser ...;          

          对哪种浏览器禁用长连接

          用在http,server,location上下文

          如 keepalive_disable msie6

       ④send_timeout time;

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

          用在http,server,location上下文

       ⑤client_body_buffer_size size;         

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

          用在http,server,location上下文

       ⑥client_body_temp_path path [level1 [level2 [level3]]];      

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

         用在http,server,location上下文

/*示例*/

/var/tmp/body 2 1 2

        2:两位16进制数字(256种变化)为一级子目录
1:一位16进制数字(16种变化)为二级子目录
2:两位16进制数字(256种变化)为三级子目录

    D.对客户端请求进行限制的配置

      ①limit_rate rate;

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

        用在http,server,location,if in location上下文

       ②limit_except method ... { ... };        

         限制对指定的请求方法之外的其他方法的使用

        仅能用在location上下文

//示例:

limit_except GET POST {
allow 192.168.1.0/32;
deny all;
} //表示除了GET和POST之外的其他请求方法仅允许192.168.1.0/32中的主机使用

     E.文件操作优化的相关配置

      ①aio on | off | threads[=pool];     

         是否启用aio功能,默认是关闭的

        用在http,server,location上下文

       ②directio size | off;

          设定直接IO的大小或关闭此功能,默认是关闭的

        用在http,server,location上下文

       ③open_file_cache off;

       open_file_cache max=N [inactive=time];      

         对打开的文件是否进行缓存

        用在http,server,location上下文

/*
nginx可以缓存以下三种信息:
(1)文件的描述符/文件大小和最近一次的修改时间
(2)打开的目录结构
(3)没有找到的或者没有权限访问的文件的信息
*/ max=N //可缓存的缓存项上限;到达后会使用LRU算法实现缓存管理
[inactive=time] //缓存项的超时时长,在此处指定的时长内未被命中的缓存项即为非活动项

        ④open_file_cache_errors on | off;    

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

        用在http,server,location上下文

       ⑤open_file_cache_min_uses number;      

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

        用在http,server,location上下文

       ⑥open_file_cache_valid time;      

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

        用在http,server,location上下文

  ngx_http_access_module:实现基于IP的访问控制功能模块    

        ①allow address | CIDR | unix: | all;

      ②deny address | CIDR | unix: | all;

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

//示例:

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:基于http协议进行basic认证

      ①auth_basic string | off;

      ②auth_basic_user_file file;

      认证用的账号密码文件,格式:name:password:commet

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

//示例:

location /admin/ {
auth_basic "admin";
uth_basic_user_file /etc/nginx/.ngxpasswd;
} //密码格式:
htpasswd命令
如:# htpasswd -c -m /etc/nginx/.ngxpasswd tom
# htpasswd -m /etc/nginx/.ngxpasswd alice

  

  ngx_http_stub_status_module:用于输出nginx的基本状态信息,用在server和location上下文

//示例:

location /basic_status {
stub_status;
} //显示效果:
Active connections: 291 //处于活动状态的客户端连接数量包括等待的连接
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106 //其中:
reading:处于读取客户端请求报文首部的连接数
writing:处于向客户端发送响应报文过程中的连接数
waiting:处于等待客户端发送请求的空闲连接数

  ngx_http_referer_module:是用来阻止访问一个在referer头域值无效请求的网站。要记住,制造要求与适当的referer字段值是很容易的,所以该模块的目的是阻止这样的请求,但要彻底阻断正常的浏览器发送请求的质量流量。还应考虑常规浏览器可能无法发送referer字段即使有效的请求。

    ①valid_referers none | blocked | server_names | string ...;

     定义合法的referer数据

      用在server,location上下文

none //请求报文首部没有referer首部

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

server_names //其值是主机名

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

regular expression //被指定的正则表达式模式匹配到的字符串;要使用~开头

//示例:

valid_referers none blocked server_names  *.example.com example.* www.example.org/galleries/~\.google\.;

if ($invalid_referer) {
return 403;
}

    

最新文章

  1. (实例篇)php 使用redis锁限制并发访问类示例
  2. GA算法-R语言实现
  3. Unit01: JAVA开发环境
  4. codeforces 424D
  5. hadoop shell 操作命令
  6. angularjs2 学习笔记(六) Form
  7. ubuntu安装svn manager
  8. [转贴]Windows下gSoap交叉编译环境的搭建
  9. Java操作XML文件 dom4j 篇
  10. 一个例子让你了解Java反射机制
  11. C GOTO使用示例
  12. struts2.0简单教程
  13. Centos7修改分区空间
  14. Java中带包(创建及引用)的类的编译
  15. jQuery图片上传前先在本地预览
  16. lilntcode-508-摆动排序
  17. GNU Autotools的使用方法
  18. java并发编程(1)并发程序的取消于关闭
  19. Have your GDX app run in the web browser
  20. windows文件打包命令

热门文章

  1. java6大原则之单一职责原则,里式替换原则
  2. thinkphp 闭包支持
  3. FastJson使用方法
  4. wrapClass
  5. (转)Windows中杀死占用某个端口的进程
  6. Mysql 数据库crash恢复
  7. leetcode--81-搜索旋转排序数组②
  8. 07.07NOIP模拟赛
  9. sqlite3-入门日记4-实现C++类封装
  10. VS code 设置侧边栏字体大小